2

Possible Duplicate:
How do I pick randomly from an array?

What is the appropriate way to ensure that a non-existent item isn't chosen?

 icons = %w[asterisk star arrow]
 random = rand(icons.length)

or

icons = %w[asterisk star arrow]
random = rand(icons.length -1)
Community
  • 1
  • 1
Slick23
  • 5,827
  • 10
  • 41
  • 72

3 Answers3

21

How about using Array#sample

[1, 2, 3].sample(1)

sample → obj
sample(random: rng) → obj
sample(n) → new_ary
sample(n, random: rng) → new_ary
Choose a random element or n random elements from the array. The elements are chosen by using random and unique indices into the array in order to ensure that an element doesn’t repeat itself unless the array already contained duplicate elements. If the array is empty the first form returns nil and the second form returns an empty array.
If rng is given, it will be used as the random number generator.

(Assuming you are more interested on the element rather than the index)

clyfe
  • 23,695
  • 8
  • 85
  • 109
1

It would be the first one.

icons = %w[asterisk star arrow]
random = rand(icons.length)

As stated in the documentation:

When the argument is an Integer or a Bignum, it returns a random integer greater than or equal to zero and less than the argument.

So, if the array is composed of 10 elements (0 .. 9), a rand(10) should return a number between 0 and 9.

Source: http://www.ruby-doc.org/core-1.9.3/Random.html

Telmo Marques
  • 5,066
  • 1
  • 24
  • 34
  • I'm going to mark this one as it directly answers the question, though I wasn't aware of sample, which seems nice and tidy. I'll upvote the others. – Slick23 Dec 19 '11 at 18:19
  • Reimplementation of a built-in method is not the correct answer to any question :) – Mark Thomas Dec 19 '11 at 20:59
  • 1
    Nevertheless, is correct and took effort, at least +1 – clyfe Dec 19 '11 at 21:53
  • @Mark Thomas, there are various reasons why reimplementation can be a correct answer. Not saying my answer follows any of that reasons, but I have to disagree with you on that one. Also, despite not answering directly the question, I agree that clyfe's answer is more correct given the purpose of the question, and should be the accepted one. – Telmo Marques Dec 19 '11 at 22:24
0
icons = %w[asterisk star arrow]
puts icons.sample
Marek Příhoda
  • 11,108
  • 3
  • 39
  • 53