From: "David A. Black" Date: 2008-08-13T01:16:56+09:00 Subject: Re: What's the easiest way to check if param[:x][:y] exists? Hi -- On Wed, 13 Aug 2008, Joshua Muheim wrote: > Hi all > > In PHP I can simply check whether $param['x']['y'] exists regardless > whether $param['x'] exists or not. > In Rails I get a NoMethodError when using > > if param[:x][:y] > .. > end > > when param[:x] is nil. So I always have to use > > if param[:x] and param[:x][:y] > .. > end > > but I think that's not very beautiful - think about a case where I have > to check whether param[:a][:b][:c][:d][:...] exists or not! > > Maybe there's a cooler way to do this? ;-) Yes: design your data structures with classes and modules and methods, instead of quintuply-nested hashes :-) But if you want to have a hash that automatically inserts a hash for an unknown key, you can do: func = lambda {|h,k| h[k] = Hash.new(&func) } hash = Hash.new(&func) I think that's the OK version.... You can also rescue NoMethodError, though that's kind of fuzzy with lots of nesting. David -- Rails training from David A. Black and Ruby Power and Light: * Advancing With Rails August 18-21 Edison, NJ * Co-taught by D.A. Black and Erik Kastner See http://www.rubypal.com for details and updates!