2

I've got an array of hashes, like this:

[
   {"name"=>"Bob Jones", "id"=>"100005913544738"},
   {"name"=>"Jimmy Smith", "id"=>"100005934513815"},
   {"name"=>"Abe Lincoln", "id"=>"100005954493955"}
]

I ultimately just want those id's in an array, like this:

[ 100005913544738, 100005934513815, 100005954493955 ]

I'm running Ruby 1.9.3.

Shpigford
  • 24,748
  • 58
  • 163
  • 252

2 Answers2

8
a = [{"name"=>"Bob Jones", "id"=>"100005913544738"},
     {"name"=>"Jimmy Smith", "id"=>"100005934513815"},
     {"name"=>"Abe Lincoln", "id"=>"100005954493955"}]

a.map{|h| h['id'].to_i}
# => [100005913544738, 100005934513815, 100005954493955]

Enumerable#map is a very handy method to be familiar with.

It also seems worth noting that if you have control over the generation of the original Array, it's more Ruby-like to use Symbols (e.g., :name and :id) rather than strings as Hash keys. There are many reasons for this.

Community
  • 1
  • 1
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
0
h = [
   {"name"=>"Bob Jones", "id"=>"100005913544738"},
   {"name"=>"Jimmy Smith", "id"=>"100005934513815"},
   {"name"=>"Abe Lincoln", "id"=>"100005954493955"}
]

h.map{|i| i.fetch("id").to_i}
#=> [100005913544738, 100005934513815, 100005954493955]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317