Reputation: 25348
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.
Upvotes: 2
Views: 2158
Reputation: 34031
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.
Upvotes: 8
Reputation: 118271
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]
Upvotes: 0