Stepan Salin Stepan Salin - 3 months ago 8
Ruby Question

analogue for ActiveRecords' "where" for plain Ruby's arrays

Let's say i have an array of hashes with identical set of keys like:

array = [
{attr1: val1, attr2: val2},
{attr1: val3, attr2: val4}
]


Thing is, i'd like to have some cool call like ActiveRecords' "where" to searh array above for specific elements. Something like

array.where(attr1: val1)


that will return all elements fitting the criteria. Using just plain Ruby.

Yes, there always is a good old
.each
but let's go full on pedal to the metal ruby-way here.

Thanks!

Answer

There is findand selectin ruby (for one or multiple results, respectively).

selected = array.select do |item|
  item[:attr1] == 'something'
end

select will pass each element of array to the block and pick those where the block returns a truthy value. find is similar but it will return the first element where the block returns a truthy value.