[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Hash.collect

Giant Cranes

2/1/2007 8:50:00 PM

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

--
Posted via http://www.ruby-....

5 Answers

James Gray

2/1/2007 8:55:00 PM

0

On Feb 1, 2007, at 2:49 PM, Giant Cranes 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 Gray II

Jos Backus

2/1/2007 8:56:00 PM

0

On Fri, Feb 02, 2007 at 05:49:38AM +0900, Giant Cranes wrote:
> 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]}

--
Jos Backus
jos at catnook.com

Brian Candler

2/1/2007 8:58:00 PM

0

On Fri, Feb 02, 2007 at 05:49:38AM +0900, Giant Cranes 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] }

Giant Cranes

2/1/2007 8:59:00 PM

0

Wonderful, thanks very much.

--
Posted via http://www.ruby-....

Gary Wright

2/1/2007 9:01:00 PM

0


On Feb 1, 2007, at 3:49 PM, Giant Cranes 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 Wright