From: Robert Klemme Date: 2011-10-12T17:42:44+09:00 Subject: Re: array of hashes On Tue, Oct 11, 2011 at 7:07 PM, Mario Ruiz wrote: > I have an array of hashes like this: > a=Array.new() > a.push({:name=>"mario",:value=>"xxx"}) > a.push({:name=>"pedro",:value=>"lsss"}) > > and I would like to get a value of the array knowing the :name by doing > something like: > a.each {|h| >  if h[:name]=="mario" then value=h[:value] > } > > but just in one line, is that possible? Here's another suggestion: you can use rescue to avoid the error you get if nothing is found: irb(main):001:0> a=[] => [] irb(main):002:0> a << {:name=>"mario",:value=>"xxx"} => [{:name=>"mario", :value=>"xxx"}] irb(main):003:0> a << {:name=>"pedro",:value=>"lsss"} => [{:name=>"mario", :value=>"xxx"}, {:name=>"pedro", :value=>"lsss"}] irb(main):004:0> a irb(main):006:0> a.find {|h| h[:name] == 'mario'}[:value] rescue nil => "xxx" irb(main):007:0> a.find {|h| h[:name] == 'missing'}[:value] rescue nil => nil It's probably cleaner though to do irb(main):008:0> r = a.find {|h| h[:name] == 'mario'} and r[:value] => "xxx" irb(main):009:0> r = a.find {|h| h[:name] == 'missing'} and r[:value] => nil Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/