Am I fundamentally misunderstanding Ruby here? I've been writing Ruby code for about 2 years now and just today stumbled on this...
ruby-1.8.7-p249 > i = true and false
=> false
ruby-1.8.7-p249 > i
=> true
Could somebody explain what's going on here please? I'm sure it's to spec, but it just seems counter intuitive to me...
In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass.
Ruby is a bit of an oddball in that while it has explicit values to represent true and false, there is no Boolean data type.
Ruby uses truthy and falsey . false and nil are falsey , everything else is truthy .
null means no data value but memory is still allocated for null. false is a boolean, it is simply not true.
The operators &&
and and
have different precedence, and =
happens to be in between.
irb(main):006:0> i = true and false
=> false
irb(main):007:0> i
=> true
irb(main):008:0> i = true && false
=> false
irb(main):009:0> i
=> false
irb(main):010:0>
The first is read as (i = true) and false
, the second as i = (true && false)
.
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