How to extract only needed attribute from an array

I have an object called Tags with id and name ==> [ tag.id , tag.name]

[1 , aaa] |

[ 3 , bbb] |

[ 5 , ccc] |

[ 6 , dfd] |

[ 7 , waf] |

[ 11 , vee] |

There is an array with the list of tags , i just want to extract all
tag.id
as a new array, what is the easiest way to do

···

--
Posted via http://www.ruby-forum.com/\.

tags.map { |t| t.id }

···

-----Original Message-----
From: superdisconnect@hotmail.com [mailto:superdisconnect@hotmail.com]
Sent: Monday, August 03, 2009 10:27 PM
To: ruby-talk ML
Subject: How to extract only needed attribute from an array

I have an object called Tags with id and name ==> [ tag.id , tag.name]

> [1 , aaa] |

> [ 3 , bbb] |

> [ 5 , ccc] |

> [ 6 , dfd] |

> [ 7 , waf] |

> [ 11 , vee] |

There is an array with the list of tags , i just want to extract all
tag.id
as a new array, what is the easiest way to do
--
Posted via http://www.ruby-forum.com/\.

Thriving K. wrote:

I have an object called Tags with id and name ==> [ tag.id , tag.name]

> [1 , aaa] |

> [ 3 , bbb] |

> [ 5 , ccc] |

> [ 6 , dfd] |

> [ 7 , waf] |

> [ 11 , vee] |

There is an array with the list of tags , i just want to extract all
tag.id
as a new array, what is the easiest way to do

Is this how your array looks?

a = [
   [1 , :aaa],
   [ 3 , :bbb],
   [ 5 , :ccc],
   [ 6 , :dfd],
   [ 7 , :waf],
   [ 11 , :vee]
]

p a.transpose[0] # ==> [1, 3, 5, 6, 7, 11]

Or:

p a.map {|b| b[0]}

···

--
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

In any case you need method #map. In 1.9* you can even do use map(&:id):

irb(main):001:0> Tag = Struct.new :id, :name
=> Tag
irb(main):002:0> a = Array.new(5) {|i| Tag.new(i, "n"*i)}
=> [#<struct Tag id=0, name="">, #<struct Tag id=1, name="n">,
#<struct Tag id=2, name="nn">, #<struct Tag id=3, name="nnn">,
#<struct Tag id=4, name="nnnn">]
irb(main):003:0> a.map(&:id)
=> [0, 1, 2, 3, 4]

Kind regards

robert

···

2009/8/4 Thriving K. <superdisconnect@hotmail.com>:

I have an object called Tags with id and name ==> [ tag.id , tag.name]

> [1 , aaa] |

> [ 3 , bbb] |

> [ 5 , ccc] |

> [ 6 , dfd] |

> [ 7 , waf] |

> [ 11 , vee] |

There is an array with the list of tags , i just want to extract all
tag.id
as a new array, what is the easiest way to do

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Joel VanderWerf wrote:

p a.transpose[0] # ==> [1, 3, 5, 6, 7, 11]

Or:

p a.map {|b| b[0]}

Or:

p a.map {|(id,name)| id }

···

--
Posted via http://www.ruby-forum.com/\.

Thank you for everyone

···

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