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
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 }