AdamNYC
AdamNYC

Reputation: 20415

slice hash in an array

I have an array of hashes like:

[{"name"=>"John Doe", "id"=>"1"}, {"name"=>"Jane Doe", "id"=>"2"}]

I would like to get back an array of id only. What would be efficient way to do so? I would prefer to avoid using a loop.

Thank you.

Upvotes: 0

Views: 1444

Answers (2)

Learning Center
Learning Center

Reputation: 21

You should do:

your_array.pluck(:id)

This is faster than map (loop)

Same use compact to remove nil

Upvotes: 2

apneadiving
apneadiving

Reputation: 115511

You should do:

your_array.map {|h| h["id"]}

But basically there is a loop in desguise.

Sidenote:

Imagine there is no id in one of the hashes, then you'd have a nil. Append compact to solve this

Upvotes: 3

Related Questions