I've been reading a technical book recently, and I think I understand it, I decided to output even the smallest details frequently.
This is an article for myself in the future.
In Ruby all values except false
and nil
are true.
In Ruby, all data / values are objects that belong to some class. Of course, true and false are no exception.
irb> true.class
=> TrueClass
irb> false.class
=> FalseClass
irb> true.class.ancestors
=> [TrueClass, Object, Kernel, BasicObject]
irb> false.class.ancestors
=> [FalseClass, Object, Kernel, BasicObject]
If all but false and nil are true, then 0
and
(empty string) are also true.
#"0" is true
irb> p 0 ? true : false
true
=> true
#"" Is also true
irb> p '' ? true : false
(irb):15: warning: string literal in condition
true
=> true
However, in other languages "0" is often false, and in JavaScript 0 and empty strings are falsy.
There is a nil?
Method to distinguish between nil and false.
irb> a = nil
=> nil
irb> a.nil?
=> true
irb> b = false
=> false
irb> b.nil?
=> false
When writing a Ruby program, nil may be mixed unexpectedly, so I often check nil, You can avoid nil objects by performing type conversion.
irb> nil.to_s
=> ""
irb> nil.to_i
=> 0
irb> nil.to_a
=> []
irb> nil.to_h
=> {}
irb> nil.to_sym
NoMethodError (undefined method `to_sym' for nil:NilClass)
to_sym
is useless.
I was confusing true/false with true/false in Ruby, but the following article was very helpful. Ruby true/false is different from true/false
Recommended Posts