17

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.

0

3 Answers 3

29

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.

2
  • 1
    While I feel pluck is a useful addition, the addition of invoke semantics in the "more general solution" link is pretty silly in Ruby, since Symbol#to_proc takes care of it for you. [1,2,3,4].map &:to_s works with no monkey-patching.
    – Mark Reed
    Oct 17, 2014 at 19:36
  • 1
    The Symbol#to_proc/[].map &:method_name shortcut won't help with hash[key], because Hash#[] needs the key parameter.
    – alxndr
    Nov 30, 2014 at 4:21
13

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 :)

1

Unpopular opinion maybe, but I wouldn't recommend using pluck on Array in Rails projects since it is also implemented by ActiveRecord and it behaves quite differently in the ORM context (it changes the select statement) :

User.all.pluck(:name) # Changes select statement to only load names
User.all.to_a.pluck(:name) # Loads the whole objects, converts to array, then filters the name out

Therefore, to avoid confusion, I'd recommend using the shorten map(&:attr) syntax on arrays:

arr.map(&:name)
8
  • What do you mean, User.all.pluck(:name) != User.all.to_a.pluck(:name)? These work differently, yes, but should produce identical arrays. Dec 14, 2022 at 15:32
  • Indeed it should, but one might experience some odds behaviors with complex queries (chained scopes, group by, custom select, etc.). Just wanted to warn people that there are two pluck implementations in rails context and they are quite different : - apidock.com/rails/Enumerable/pluck - apidock.com/rails/ActiveRecord/Calculations/pluck Also map(&:attr) performs caching, while fetch(:attr) always reruns the query on the database.
    – Ghis
    Dec 15, 2022 at 16:13
  • "but one might experience some odds behaviors" - no, I don't think so. I can't think of a query that would make these two diverge. I am very interested in seeing one. Dec 15, 2022 at 16:20
  • User.all.map(&:name) is a terribly wasteful way of fetching just one column, btw. Waste all around: bandwidth, memory footprint, CPU time. Dec 15, 2022 at 16:21
  • 1
    Yes, in most cases, i would recommend using pluck with ActiveRecord and map with arrays, just to avoid confusion (pluck is just an alias to map with arrays, while pluck and map behave very differently with ActiveRecord). That was the point. Finnally, in order to answer your interest : This works : User.select('COUNT(*) AS role_count').group(:"users.role").map(&:role_count) This doesn't : User.select('COUNT(*) AS role_count').group(:"users.role").pluck(:role_count ) (ERROR: column "role_count" does not exist)
    – Ghis
    Dec 15, 2022 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.