3

Given an really big array/hash, for example, users:

users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'jeff',   'age': 32 },
  ...
  { 'user': 'fred',   'age': 40 }
];

If you apply Lodash's pluck function*:

_.pluck(users, 'user');

You get this result:

-> ['barney', 'jeff', ..., 'fred']

Does Ruby have a similarly convenient function that will get only a certain key of the array/hash without iterating it? I know Rails has a function called pluck but it is for ActiveRecords. Any suggestions for how to accomplish this on arrays?

*pluck was apparently replaced by map since this question was written

Community
  • 1
  • 1
Javier del Saz
  • 846
  • 1
  • 9
  • 16
  • I know I answered already, but it's actually not clear what language you're asking about. The title leads me to believe Ruby, but the code samples look like javascript. – acsmith Jan 03 '16 at 02:10
  • Yes, im asking about Ruby, but the example was taken from JS, with a example in JS in order to be clear what I would want to have in Ruby – Javier del Saz Jan 03 '16 at 22:00

2 Answers2

4

I don't think there is on in the standard library, but it is easy to accomplish this with a block:

users.map { |element| element[:user] }

P.S.: since you used the colon style hash, each key in your hash is a symbol, and must be accessed as element[:].

Harper Maddox
  • 540
  • 4
  • 8
2

It seems like you want #map, which takes each element of an array and replaces it with the result of a block.

users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'jeff', 'age': 32 },
  ...
  { 'user': 'fred',   'age': 40 }
]

users.map {|u| u['user'] } # => ['barney', 'jeff', ..., 'fred']
acsmith
  • 1,466
  • 11
  • 16