Shpigford
Shpigford

Reputation: 25348

Pull key value from an array of hashes?

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

Answers (2)

Darshan Rivka Whittle
Darshan Rivka Whittle

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

Arup Rakshit
Arup Rakshit

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

Related Questions