Ruby: Clean code for checking nil /false conditional statement?
ruby
Solution
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
Problem
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