Hash.collect


#1

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


#2

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


#3

Wonderful, thanks very much.


#4

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


#5

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.


#6

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