0

With ruby on rails, ruby, how can I randomly select either 4 or 5?

lucapette
  • 20,564
  • 6
  • 65
  • 59
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • 6
    http://xkcd.com/221/ – Felix Kling Feb 14 '12 at 17:36
  • possible duplicate of [How to get a random number in Ruby?](http://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby) – Felix Kling Feb 14 '12 at 17:38
  • 1
    I understand closing this as a duplicate, but why the downvotes? It's clearly worded, on topic, and something that would not be obvious to a new Ruby programmer. – jdl Feb 14 '12 at 18:04

4 Answers4

5

Just use Ruby's rand function:

4+rand(2)
=> 4
4+rand(2)
=> 5
4+rand(2)
=> 5
coudy
  • 13,218
  • 5
  • 23
  • 26
5

I like a nice simple one liner.

(4..5).to_a.sample
MrDanA
  • 11,489
  • 2
  • 36
  • 47
3
four_or_five = rand(2) == 0 ? 4 : 5

Since rand(num) chooses a value between 0 and num, non-inclusive, there's a 50% chance of 0 being chosen. Thus, four_or_five will be 4 or 5 with equal probability.

Eric Hu
  • 18,048
  • 9
  • 51
  • 67
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
2

In Ruby 1.9.3 I think you can just do:

rand(4..5)
steenslag
  • 79,051
  • 16
  • 138
  • 171
AlistairH
  • 3,139
  • 2
  • 21
  • 19