From: 7stud -- Date: 2008-05-02T18:32:31+09:00 Subject: Re: Extracting a value from an array Albert Schlef wrote: > I have the following array: > > headers = [ > { :name => 'user-agent', :value => 'blah blah' }, > { :name =>'content-type', :value => 'text/html' }, > { :name => 'pragma', :value => 'no-cache' }, > { :name =>'content-length', :value => '30' }, > { :name =>'content-type', :value => 'text/html' }, > ] > > Now, I want to extract the :value of the first header of a specific > :name. For example, I want to extract the :value of the 'content-type' > header. > > So I do: > > content_length = nil > headers.each { |header| > content_length = header[:value] if header[:name] == 'content-length' > } > > However, this code is not very "beautiful", and I was wondering if > there's some other, more clearer way to do this. > > (And it's fine with me if we take the :value of a 'content-type' header > which is not necessarily the first in the array (in the code above I > actually pick the last header). Also, I don't very much mind about > performance because there are a few headers. I'm simply looking for a > clear, straightforward code for this simple task.) headers = [ { :name => 'user-agent', :value => 'blah blah' }, { :name =>'content-type', :value => 'text/html' }, { :name => 'pragma', :value => 'no-cache' }, { :name =>'content-length', :value => '30' }, { :name =>'content-type', :value => 'text/html' }, ] content_type = "" headers.each do |hash| if hash[:name] == "content-type" content_type = hash[:value] break end end puts content_type -- Posted via http://www.ruby-forum.com/.