From: Steve Howell Date: 2010-10-14T14:15:11+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? On Oct 11, 1:02 pm, Charles Calvert wrote: > I'm using Ruby 1.8.7 patchlevel 249 > > Is there a more idiomatic way to do the following? > > var = hash[key].nil? ? nil : hash[key].downcase > > Note that if hash[key] is nil, I want nil assigned to var, so this > won't work: > > var = hash[key].downcase unless hash[key].nil? > > Obviously I could do this, but I'm trying to keep it on one line: > > var = hash[key] > var = var.downcase unless var.nil? > I'm not sure if this is the most common idiom, but you can write a helper method like "try" that chains method calls but aborts nicely to nil as soon as an object dereference (or the primary object itself) evaluates to nil. The example below is slightly fancier than you might need, as it supports multiple dereferences. Scroll down to the bottom to see its usage. $ cat foo.rb def try(obj, *args) for arg in args return nil if obj.nil? obj = obj.send(arg) end return obj end class Mission end class Department def name 'HR' end def mission return nil end end class Employee def department return Department.new() end def name # oops, no name field return nil end end emp = nil puts try(emp, :mission, :department, :name) emp = Employee.new puts try(emp, :department, :name) $ ruby foo.rb nil HR