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.
Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.
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.”
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.
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.
There is a simple (although not very exciting) way to do this:
rand(2) == 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With