To make it simple, i have a list of Products.
Now i want to create a method and will generate me a random Product each time.
How do i achieve that.
To make it simple, i have a list of Products.
Now i want to create a method and will generate me a random Product each time.
How do i achieve that.
assuming you have an array products of Products, then you can select a random Product by the following code:
randon_product = products.sample
In 1.9 you have [].sample
and in 1.8 you have [].choice
. There is a gem called backports that harmonizes this and other differences, or you could do it yourself like this:
class Array
def sample
choice
end
end unless Array.method_defined? :sample
In Ruby 1.8, the simplest way is probably Array#choice
irb(main):005:0> 5.times {puts (1..100).to_a.choice}
14
92
84
65
9
=> 5
irb(main):006:0> [5,3,234,234,3,2,2,2].choice
=> 3
EDIT In Ruby 1.9 it is called sample
, not choice
.