With ruby on rails, ruby, how can I randomly select either 4 or 5?
Asked
Active
Viewed 317 times
0
-
6http://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
-
1I 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 Answers
5
I like a nice simple one liner.
(4..5).to_a.sample

MrDanA
- 11,489
- 2
- 36
- 47
-
4
-
+1 for using `Array#sample`. However, no need to create a Range. Simply use `%w( 4 5 ).sample`. – Simone Carletti Feb 14 '12 at 17:37
-
Ha that's true, Sergio. I just usually go straight to ranges because usually it's between larger numbers (like `(1..100)`) but yeah in this case that be easier. – MrDanA Feb 14 '12 at 17:38
-
1
-
@SergioTulentsev You're right, but it depends on what you need to do. ;) – Simone Carletti Feb 14 '12 at 17:59
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