Stepan Salin Stepan Salin - 1 month ago 5x
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
but let's go full on pedal to the metal ruby-way here.



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

selected = do |item|
  item[:attr1] == 'something'

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.