Hey Nick,
I remember writing a method a while back that dealt with this problem.
I'm not exactly sure where that code went, but here's what I remember:
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
hash = nil
end
end
return hash
end
end
# Usage:
puts({:a => {:b => {:c => "Hello, world!"}}}.descend(:a, :b, :c)) # =>
"Hello, World!"
Although I like your solution as well, you might want something more
explicit, in case you still wanted nil to act normally in other
contexts.
Cheers,
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
-~----------~----~----~----~------~----~------~--~---