What would I do , just use local variables to ease your burden:
unless (p=foo[:parent]) && (c=p[:child]) && !c.blank?
But let them learn alternatives, for fun & hellip;
If you cannot change your data structure (this is a hash, by the way, not an array), you can use Ruby andand in combination with Rails try
as lazy ways to call methods on objects that can be nil
objects.
You can alternatively change the data structure to hashes that return empty auto-living hashes when you request a key that does not exist:
mine = Hash.new{ |h,k| Hash.new(&h.default_proc) } mine[:root] = { dive:42 } p mine[:root][:dive] #=> 42 p mine[:ohno][:blah][:whee] #=> {} p mine[:root][:blah][:whee] #=> undefined method `[]' for nil:NilClass (NoMethodError)
However, you will need to ensure that every object in your hierarchy is one of these hashes (which I obviously could not do for the content :dive
, which led to an error).
For alternative entertainment, you can add your own magic search method:
class Hash def divedive(*keys) obj = self keys.each do |key| return obj unless obj && obj.respond_to?(:[]) obj = obj[key] end obj end end if myarray.divedive(:parent,:child).blank? # ...
source share