Jano Svitok
5/2/2008 9:27:00 AM
On Fri, May 2, 2008 at 11:02 AM, Albert Schlef <albertschlef@gmail.com> 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.select {|header| header[:name] == 'content-length'}.first[:value]
or even better:
headers.find {|header| header[:name] == 'content-length'}[:value]