With ruby on rails, ruby, how can I randomly select either 4 or 5?
- 6xkcd.com/221Felix Kling– Felix Kling2012-02-14 17:36:20 +00:00Commented Feb 14, 2012 at 17:36
- possible duplicate of How to get a random number in Ruby?Felix Kling– Felix Kling2012-02-14 17:38:56 +00:00Commented Feb 14, 2012 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– jdl2012-02-14 18:04:39 +00:00Commented Feb 14, 2012 at 18:04
Add a comment |
4 Answers
I like a nice simple one liner.
(4..5).to_a.sample 5 Comments
Sergio Tulentsev
Why overcomplicating?
[4, 5].sampleSimone Carletti
+1 for using
Array#sample. However, no need to create a Range. Simply use %w( 4 5 ).sample.MrDanA
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.Sergio Tulentsev
@SimoneCarletti: that would be array of strings. Not cool.
Simone Carletti
@SergioTulentsev You're right, but it depends on what you need to do. ;)