Hash.collect

G

Giant Cranes

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
 
J

James Edward Gray II

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 Gray II
 
J

Jos Backus

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.

a.collect {|e| e[:name]}
 
B

Brian Candler

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] }
 
G

gwtmp01

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 Wright
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,230
Messages
2,571,161
Members
47,794
Latest member
LucretiaEl

Latest Threads

Top