Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way to access hash values in array of hashes?

Tags:

ruby

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.

like image 346
Jeff Dickey Avatar asked Nov 14 '13 00:11

Jeff Dickey


People also ask

How to access array of hashes in Ruby?

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.

How to push hash into array in Ruby?

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.

What is hash array?

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.


2 Answers

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.

like image 143
Ken Y-N Avatar answered Sep 28 '22 00:09

Ken Y-N


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

like image 29
khaled_gomaa Avatar answered Sep 28 '22 00:09

khaled_gomaa