From: Peter Vandenabeele Date: 2011-10-12T02:58:26+09:00 Subject: Re: array of hashes --0016364ed5241a3a4c04af09a7e5 Content-Type: text/plain; charset=UTF-8 On Tue, Oct 11, 2011 at 7:44 PM, botp wrote: > On Wed, Oct 12, 2011 at 1:07 AM, Mario Ruiz wrote: > > and I would like to get a value of the array knowing the :name by doing > > a.find{|x| x[:name]=="pedro"}[:value] > #=> "lsss" > I tried this also, but stopped when I figured out that if there is no match for the name, this will cause an exception... I did not see an elegant solution for that case, with the data structure that the OP proposes. $ irb 001:0> a = [{:name => "pedro", :value => "Isss"}] => [{:name=>"pedro", :value=>"Isss"}] 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 from (irb):3 from /home/peterv/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `
' > > but why not directly use a hash, eg, > > h={} > #=> {} > h["mario"]="xxx" > #=> "xxx" > h["pedro"]="lsss" > #=> "lsss" > > h["pedro"] > #=> "lsss" > I agree. 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). That would make it really useful to make a better implementation (like you propose) where you can look-up directly, based on the :name. Thx, Peter --0016364ed5241a3a4c04af09a7e5--