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

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

On Tue, Oct 26, 2010 at 8:55 AM, Karcsony K. [email protected] wrote:


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 # => [#, #, #]
users.map { |user| user.name } # => [“Stephan”, “Carol”, “Lizi”]
users.map { |user| user.id } # => [1, 2, 3]

On Oct 26, 9:28am, Josh C. [email protected] wrote:

name=“Carol”>, #]
users.map { |user| user.name } # => [“Stephan”, “Carol”, “Lizi”]
users.map { |user| user.id } # => [1, 2, 3]

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs