MatlabDoug
MatlabDoug

Reputation: 5714

How to cast 1 and 0 to true and false in Ruby. Want a boolean or logical out

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

Answers (4)

yagooar
yagooar

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

jerhinesmith
jerhinesmith

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

ezpz
ezpz

Reputation: 12027

[true,false].shuffle or [true,false].sort { rand }

def get_bool
   [true,false].shuffle.shift
end

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838096

There is a simple (although not very exciting) way to do this:

rand(2) == 1

Upvotes: 26

Related Questions