Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Clean code for checking nil /false conditional statement?

Tags:

ruby

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

like image 791
TheOneTeam Avatar asked Jul 25 '13 07:07

TheOneTeam


People also ask

How do you check if something is nil in Ruby?

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

Is nil considered false in Ruby?

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

Is 0 true or false in Ruby?

Zero is a value, and ALL values in Ruby are evaluated to true, EXCEPT for FALSE and NIL.

How do you negate a condition in Ruby?

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!"


1 Answers

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:

  • if value does not exist, the &. operator will throw, try will just return nil (preferable or not?)(note: try! would also throw).
  • when cascading 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
like image 99
nathanvda Avatar answered Oct 19 '22 22:10

nathanvda