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
  • 307
  • 2
  • 6
  • 16

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
  • 45,173
  • 14
  • 109
  • 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
  • 139,415
  • 24
  • 238
  • 326
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
  • 82,964
  • 16
  • 166
  • 221
  • 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
  • 14,775
  • 14
  • 52
  • 70