Forum: Ruby Hash.collect

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Giant C. (Guest)
on 2007-02-01 22:49
Hi,

I am pulling my hair out trying to figure out the following problem (my
fault not rubys):

I have an array of hashes as follows:

a = Array.new
a << {:name => 'tony', :age => 23}
a << {:name => 'mary', :age => 57}
a << {:name => 'dom', :age => 17}

I am trying to create an array with one attribute from each hash:

['tony', 'mary', 'dom']

Any clues on how I should do this would be much appreciated.

Thanks,
GiantCranes
James G. (Guest)
on 2007-02-01 22:56
(Received via mailing list)
On Feb 1, 2007, at 2:49 PM, Giant C. wrote:

> I have an array of hashes as follows:
>
> a = Array.new
> a << {:name => 'tony', :age => 23}
> a << {:name => 'mary', :age => 57}
> a << {:name => 'dom', :age => 17}
>
> I am trying to create an array with one attribute from each hash:
>
> ['tony', 'mary', 'dom']

 >> a = Array.new
=> []
 >> a << {:name => 'tony', :age => 23}
=> [{:name=>"tony", :age=>23}]
 >> a << {:name => 'mary', :age => 57}
=> [{:name=>"tony", :age=>23}, {:name=>"mary", :age=>57}]
 >> a << {:name => 'dom', :age => 17}
=> [{:name=>"tony", :age=>23}, {:name=>"mary", :age=>57},
{:name=>"dom", :age=>17}]
 >> a.map { |e| e[:name] }
=> ["tony", "mary", "dom"]

Hope that helps.

James Edward G. II
Giant C. (Guest)
on 2007-02-01 22:58
Wonderful, thanks very much.
Brian C. (Guest)
on 2007-02-01 23:02
(Received via mailing list)
On Fri, Feb 02, 2007 at 05:49:38AM +0900, Giant C. wrote:
> a = Array.new
> a << {:name => 'tony', :age => 23}
> a << {:name => 'mary', :age => 57}
> a << {:name => 'dom', :age => 17}
>
> I am trying to create an array with one attribute from each hash:
>
> ['tony', 'mary', 'dom']
>
> Any clues on how I should do this would be much appreciated.

b = a.collect { |e| e[:name] }
unknown (Guest)
on 2007-02-01 23:06
(Received via mailing list)
On Feb 1, 2007, at 3:49 PM, Giant C. wrote:
> I am trying to create an array with one attribute from each hash:
>
> ['tony', 'mary', 'dom']
>
> Any clues on how I should do this would be much appreciated.

a.map { |h| h[:name] }

Gary W.
Jos B. (Guest)
on 2007-02-01 23:29
(Received via mailing list)
On Fri, Feb 02, 2007 at 05:49:38AM +0900, Giant C. wrote:
> a << {:name => 'dom', :age => 17}
>
> I am trying to create an array with one attribute from each hash:
>
> ['tony', 'mary', 'dom']
>
> Any clues on how I should do this would be much appreciated.

a.collect {|e| e[:name]}
This topic is locked and can not be replied to.