Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i = true and false in Ruby is true?

Tags:

ruby

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...

like image 669
alex Avatar asked May 10 '10 12:05

alex


People also ask

Is False an object in Ruby?

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.

Is boolean a Ruby?

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.

Is nil false in rails?

Ruby uses truthy and falsey . false and nil are falsey , everything else is truthy .

What is difference between nil and false in Ruby?

null means no data value but memory is still allocated for null. false is a boolean, it is simply not true.


1 Answers

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).

like image 141
Thomas Avatar answered Oct 20 '22 00:10

Thomas