From: Gareth Adams Date: 2006-09-27T08:29:48+09:00 Subject: Re: Accessing Nested Hashes Directly atraver gmail.com gmail.com> writes: > However, sometimes the "name" element might not come over the wire > (through no fault of Ruby's nor Rails' -- it's just a problem we have > to deal with in our system). In this case, Ruby will throw a > NoMethodError on nil.[] because we tried to access the value at "given" > on an element that does not exist. Furthermore, sometimes the "user" > element does not exist, either! This led me to code that looks like > this: > > if params["body"]["user"] > if params["body"]["user"]["name"] > first_name = params["body"]["user"]["name"]["given"] > end > end > > That's not very elegant when you're doing it with many (15 - 30) > fields. I use something like the following, although it would also look unweildy when chained together a lot hsh.fetch(:key, {}) # returns either hsh[:key], or {} if !hsh.has_key?(:key) so hsh.fetch(:key1, {}).fetch(:key2, nil) # will work as expected, silently returning nil on error Gareth