0

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.

user901790
  • 299
  • 3
  • 6
  • 17

4 Answers4

7

assuming you have an array products of Products, then you can select a random Product by the following code:

randon_product = products.sample
ennuikiller
  • 46,381
  • 14
  • 112
  • 137
2

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
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
1

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.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • See DigitalRoss's answer for a nice way to allow the use of `sample` in all Ruby versions. [Here's the change log for Ruby 1.9.1 showing that choice was removed](http://svn.ruby-lang.org/repos/ruby/branches/ruby_1_9_1/NEWS) – Ray Toal Sep 15 '11 at 16:24
0
array = [product1, product2, product3]

puts array[rand(array.size)]
evfwcqcg
  • 15,755
  • 15
  • 55
  • 72