From: Brian Candler Date: 2011-10-12T05:44:06+09:00 Subject: Re: array of hashes Peter Vandenabeele wrote in post #1026119: > 002:0> a.find{|x| x[:name]=="pedro"}[:value] > => "Isss" > 003:0> a.find{|x| x[:name]=="mario"}[:value] > NoMethodError: undefined method `[]' for nil:NilClass That's the nil chaining problem. I usually just write something like res = if val = a.find{|x| x[:name]=="mario"} v[:value] end There is also: res = a.find{|x| x[:name]=="mario"}[:value] rescue nil although that might mask other exceptions that you don't want hidden. Various additions to Object have been proposed to make the it unnecessary to guard against nils in chained methods. For example see number 9 here: http://yehudakatz.com/2009/08/24/my-10-favorite-things-about-the-ruby-language/ Something similar found its way into Rails 2.3: http://ozmm.org/posts/try.html (Instead of just swallowing nils, it checks for the existence of a method before calling it) > A general question I have is: are there hashes or arrays in Ruby > that offer a logarithmic look-up cost (e.g. implemented with a > btree, like an indexed column on a database). Hashes are dynamically sized and will give you logarithmic lookup cost. There are third-party libraries for trees; the main reason for using a tree instead is so that you can insert nodes at particular places and retrieve them from the same place. -- Posted via http://www.ruby-forum.com/.