From: hadley wickham Date: 2006-09-28T02:37:11+09:00 Subject: Re: Accessing Nested Hashes Directly On 9/26/06, atraver@gmail.com wrote: > I've been having a problem for a while with Ruby where accessing a hash > within a hash will fail if the first hash is nil. As an example, Rails > accepts XML input to an action by passing it through REXML. On an XML > document like this: > > > > > Tony > Robbins > > > > > You will receive a hash that looks like this (within the params hash): > > "body" => { "user" => { "name" => { "given" => "Tony", "family" => > "Robbins" } } } > > Thus, you can access the elements like this: > > params["body"]["user"]["name"]["given"] > > 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 also tried doing it with exceptions: > > begin > first_name = params["body"]["user"]["name"]["given"] > rescue NoMethodError > end What about: first_name = params["body"]["user"]["name"]["given"] rescue nil Hadley