In this code:
arr = [ { id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]
arr.map { |h| h[:id] } # => [1, 2, 3]
Is there a cleaner way to get the values out of an array of hashes like this?
Underscore.js has pluck, I'm wondering if there is a Ruby equivalent.
In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.
Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.
An array of hashes is useful when you have a bunch of records that you'd like to access sequentially, and each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures in this chapter.
If you don't mind monkey-patching, you can go pluck yourself:
arr = [{ id: 1, body: 'foo'}, { id: 2, body: 'bar' }, { id: 3, body: 'foobar' }]
class Array
def pluck(key)
map { |h| h[key] }
end
end
arr.pluck(:id)
=> [1, 2, 3]
arr.pluck(:body)
=> ["foo", "bar", "foobar"]
Furthermore, it looks like someone has already generalised this for Enumerables, and someone else for a more general solution.
Now rails support Array.pluck
out of the box. It has been implemented by this PR
It is implemented as:
def pluck(key)
map { |element| element[key] }
end
So there is no need to define it anymore :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With