In fact, here's a better/ high performance version:

class Hash
  def descend(*keys)
    keys = [keys].flatten.compact

    hash = self

    keys.each_with_index do |key, i|
      if hash.respond_to?(:has_key?) and hash.has_key?(key)
        hash = hash[key]
      else
        return nil
      end
    end

    return hash
  end
end

# Usage:

puts({:a => {:b => {:c => "Hello, world!"}}}.descend(:a, :b, :c)) # =>  
"Hello, World!"
puts({:a => {:b => {:c => "Hello,  
world!"}}}.descend(:a, :b, :c, :d, :e, :f, :g, :h, :i, :j)) # => nil

The second usage above will stop at :d since it's returned before  
having to iterate over all the others, hence it being faster.

-Jordan


On Aug 17, 2009, at 12:37 PM, Nick Zadrozny wrote:

> So I had a moment of disgust over all the nil object checking I'm  
> doing when grabbing values that may or may not be present in a multi- 
> level hash.
>
> You know the code,
>
> @foo.whatsit = params[:widgets][:thingamabob] if params[:widgets] &&  
> params[:widgets][:thingamabob]
>
> Why not just define [] on NilClass and be done with it?
>
> class NilClass
>   def [](index=nil)
>     nil
>   end
> end
>
> The purist in me revolts a little bit at this idea. But the  
> pragmatist would love to quit making all these nil object checks  
> when I really don't care about them.
>
> I suppose I could just do…
>
> @foo.whatsit = params[:widgets][:thingamabob] rescue nil
>
> …but that also seems a bit shady, though I certainly can recall  
> seeing examples of it in the wild.
>
> Do any of you wrestle with this? Perhaps you have better suggestions  
> to save me some typing while appeasing my inner pedant? Or maybe you  
> can tell me that both of the above are just fine, you do them all  
> the time, and I should quit splitting hairs?
>
> -- 
> Nick Zadrozny
>
> >



---------------------------------------------------------------

Jordan A. Fowler
E-mail: [email protected]
Website: http://www.jordanfowler.com
Phone: (619) 339-6752


--~--~---------~--~----~------------~-------~--~----~
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
-~----------~----~----~----~------~----~------~--~---

Reply via email to