On Oct 11, 1:02=A0pm, Charles Calvert <cb... / yahoo.com> wrote:
> I'm using Ruby 1.8.7 patchlevel 249
>
> Is there a more idiomatic way to do the following?
>
> var =3D 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 =3D hash[key].downcase unless hash[key].nil?
>
> Obviously I could do this, but I'm trying to keep it on one line:
>
> var =3D hash[key]
> var =3D 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 =3D 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 =3D nil
  puts try(emp, :mission, :department, :name)
  emp =3D Employee.new
  puts try(emp, :department, :name)

  $ ruby foo.rb
  nil
  HR