Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 778
MatlabDoug Avatar asked Jan 14 '10 21:01

MatlabDoug


People also ask

Is 0 true or false in Ruby?

Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.

Does Ruby have boolean?

Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”

What the difference is between false and nil in Ruby?

We saw in Keywords that true , false , and nil are keywords in Ruby. true and false are the two Boolean values, and they represent truth and falsehood, yes and no, on and off. nil is a special value reserved to indicate the absence of value. Each of these keywords evaluates to a special object.

How do you compare boolean values in Ruby?

In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.


1 Answers

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

rand(2) == 1
like image 119
Mark Byers Avatar answered Sep 25 '22 23:09

Mark Byers