0

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

lucapette
  • 20,249
  • 5
  • 64
  • 59
AnApprentice
  • 103,298
  • 185
  • 610
  • 989
  • 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
  • 12,480
  • 5
  • 20
  • 25
5

I like a nice simple one liner.

(4..5).to_a.sample
MrDanA
  • 11,293
  • 2
  • 35
  • 46
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
  • 17,750
  • 9
  • 50
  • 67
Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354
2

In Ruby 1.9.3 I think you can just do:

rand(4..5)
steenslag
  • 76,334
  • 16
  • 131
  • 165
AlistairH
  • 3,049
  • 1
  • 19
  • 19