Reputation: 5714
I need to index into a hash that I have defined in terms of "true" and "false"
colorHash = Hash.new { |hash, key| hash[key] = {} }
colorHash["answers"][true] = "#00CC00"
colorHash["answers"][false] = "#FFFFFF"
For testing purposes, I am indexing with rand(2) and that fails. If I index with true it works.
I was looking for something like
rand(2).logical
but find nothing.
Upvotes: 11
Views: 4604
Reputation: 15979
I think this is one of the coolest ways, and #sample is one of the less known Array methods:
[true, false].sample
Edit: This is only valid in Ruby >= 1.9
Upvotes: 5
Reputation: 15492
How about something like this?
[true,false][rand(2)]
That is, return a random result from the true/false array. It's certainly more verbose than rand(2) == 1
, though.
Upvotes: 6
Reputation: 12027
[true,false].shuffle
or [true,false].sort { rand }
def get_bool
[true,false].shuffle.shift
end
Upvotes: 1
Reputation: 838096
There is a simple (although not very exciting) way to do this:
rand(2) == 1
Upvotes: 26