embedded hash in array to selected-array

K

Karácsony K.

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
 
J

Josh Cheek

Hi!

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

How can i make a users_names, which will contain ['Stephan', 'Carol',
'Lizi'] ?
Thanks:Koli
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 =3D Struct.new:)id ,:name)
users =3D [ User.new(1,'Stephan') , User.new(2,'Carol') , User.new(3,'Lizi'=
) ]
users # =3D> [#<struct User id=3D1, name=3D"Stephan">, #<struct User id=3D2=
,
name=3D"Carol">, #<struct User id=3D3, name=3D"Lizi">]
users.map { |user| user.name } # =3D> ["Stephan", "Carol", "Lizi"]
users.map { |user| user.id } # =3D> [1, 2, 3]
 
W

w_a_x_man

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

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]

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top