Embedded hash in array to selected-array

Hi!

I have this array:
users = [ { :id => 1, :name => 'Stephan'}, { :id => 2, :name =>
'Carol'}, { :id => 3, :name => 'Lizi'} ]

How can i make a users_names, which will contain ['Stephan', 'Carol',
'Lizi'] ?
Thanks:Koli

···

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

users.map {|us| us[:name]}

···

On Tue, Oct 26, 2010 at 9:55 AM, Karácsony K. <koli14@gmail.com> wrote:

Hi!

I have this array:
users = [ { :id => 1, :name => 'Stephan'}, { :id => 2, :name =>
'Carol'}, { :id => 3, :name => 'Lizi'} ]

How can i make a users_names, which will contain ['Stephan', 'Carol',
'Lizi'] ?
Thanks:Koli

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

It seems you are using hashes to collect related data. If its just a quick
one time use, a struct might be easier to work with. If you want something
more robust, perhaps a class.

User = Struct.new(:id ,:name)
users = [ User.new(1,'Stephan') , User.new(2,'Carol') , User.new(3,'Lizi') ]
users # => [#<struct User id=1, name="Stephan">, #<struct User id=2,
name="Carol">, #<struct User id=3, name="Lizi">]
users.map { |user| user.name } # => ["Stephan", "Carol", "Lizi"]
users.map { |user| user.id } # => [1, 2, 3]

···

On Tue, Oct 26, 2010 at 8:55 AM, Karácsony K. <koli14@gmail.com> wrote:

Hi!

I have this array:
users = [ { :id => 1, :name => 'Stephan'}, { :id => 2, :name =>
'Carol'}, { :id => 3, :name => 'Lizi'} ]

How can i make a users_names, which will contain ['Stephan', 'Carol',
'Lizi'] ?
Thanks:Koli

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

Or even:
users.map( &:name )
    ==>["Stephan", "Carol", "Lizi"]
VERSION
    ==>"1.8.7"

···

On Oct 26, 9:28 am, Josh Cheek <josh.ch...@gmail.com> wrote:

On Tue, Oct 26, 2010 at 8:55 AM, Karácsony K. <kol...@gmail.com> wrote:
> Hi!

> I have this array:
> users = [ { :id => 1, :name => 'Stephan'}, { :id => 2, :name =>
> 'Carol'}, { :id => 3, :name => 'Lizi'} ]

> How can i make a users_names, which will contain ['Stephan', 'Carol',
> 'Lizi'] ?
> Thanks:Koli

> --
> Posted viahttp://www.ruby-forum.com/.

It seems you are using hashes to collect related data. If its just a quick
one time use, a struct might be easier to work with. If you want something
more robust, perhaps a class.

User = Struct.new(:id ,:name)
users = [ User.new(1,'Stephan') , User.new(2,'Carol') , User.new(3,'Lizi') ]
users # => [#<struct User id=1, name="Stephan">, #<struct User id=2,
name="Carol">, #<struct User id=3, name="Lizi">]
users.map { |user| user.name } # => ["Stephan", "Carol", "Lizi"]
users.map { |user| user.id } # => [1, 2, 3]