I\'m just breaking into the ruby world and I could use a helping hand.
Suppose b
is nil
.
I\'d like the following code to return n
You can use the inline rescue:
x = a.b.c("d").e rescue nil
x
will be nil
if b
is nil
.
Or, as someone commented in that link, you can use the andand gem (see docs):
x = a.andand.b.andand.c("d").andand.e
"try" is very clean, as lucapette said. More generally, you could also use a begin-rescue-end block too, depending on your situation.
begin
a.b.c("d").e
rescue NoMethodError=>e
return nil
end
I've made the may_nil
gem for this. https://github.com/meesern/may_nil
Like @Sony Santos's safe_nils answer it uses a block to wrap the method chain and rescues NoMethodError, but will check for nil (and so will properly raise an exception for other classes).
require `may_nil`
may_nil {a.b.c("d").e} => nil (or the end result)
may_nil {0.b.c("d").e} => Exception: NoMethodError (b on Fixnum)
Unlike andand
or ike
's maybe
you don't need to pepper the method chain.
a.andand.b.andand.c("d").andand.e
==>
may_nil{ a.b.c("d").e }