0

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

3
  • 6
    xkcd.com/221 Commented Feb 14, 2012 at 17:36
  • possible duplicate of How to get a random number in Ruby? Commented Feb 14, 2012 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. Commented Feb 14, 2012 at 18:04

4 Answers 4

5

Just use Ruby's rand function:

4+rand(2) => 4 4+rand(2) => 5 4+rand(2) => 5 
Sign up to request clarification or add additional context in comments.

Comments

5

I like a nice simple one liner.

(4..5).to_a.sample 

5 Comments

Why overcomplicating? [4, 5].sample
+1 for using Array#sample. However, no need to create a Range. Simply use %w( 4 5 ).sample.
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.
@SimoneCarletti: that would be array of strings. Not cool.
@SergioTulentsev You're right, but it depends on what you need to do. ;)
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.

Comments

2

In Ruby 1.9.3 I think you can just do:

rand(4..5) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.