I always meet this Ruby problem, I want to write it more cleanly.
var a can be nil
a.value can also be nil
a.value has possible true or false value
if (not a.nil?) && (not a.value.nil?) && a.value == false
puts "a value is not available"
else
puts "a value is true"
end
The problem is that the conditional statement is too clumsy and hard to read.
How can I improve the checking nil
and false
conditional statement?
Thanks, I am a Ruby newbie
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
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.”
Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.
In Ruby, we can negate a condition by appending the exclamation (!) before the condition. That will reverse the result of the condition. print "Hi, I am negated!"
Ruby on rails has an extension called try
which allows you to write:
if a.try(:value) == false
which is very clean. Without try
, you can just write
if a && a.value == false
If a.value
is nil, it is not false, so that is ok :)
If it is possible that a.value
is not defined (which would raise an exception), I would write that as follows:
if a && a.respond_to?(:value) && a.value == false
[UPDATE: after ruby 2.3]
Since ruby 2.3 there is an even shorter version:
if a&.value == false
which is almost equivalent to a.try(:value)
(but is pure ruby). Differences:
value
does not exist, the &.
operator will throw, try
will just return nil (preferable or not?)(note: try!
would also throw). try
or &.
they also handle false
differently. This follows logically from previous difference, try
will return nil, while &.
will throw because false
knows no methods :P 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