Ron Schwartz
Ron Schwartz

Reputation: 31

Searching for a specifc item in array

I have an array of objects and I need to find the last element that matches a specific condition. I tried to do it with each_reverse, but it ended up with too much of a code:

matching_item = nil

items.reverse_each do |item|
  if (item.type_id == 10)
    matching_item = item
    break
  end
end

Is it possible to make it shorter?

Upvotes: 2

Views: 93

Answers (3)

Justin Ko
Justin Ko

Reputation: 46826

Try:

matching_item = items.reverse.find{ |i| i.type_id == 10 }

Upvotes: 5

steenslag
steenslag

Reputation: 80065

items.reverse_each.detect{|item| iterm.type_id == 10}
#or
items[items.rindex{|item| item.type_id == 10}]

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270609

I would probably use Array#select and return the last match:

matching_item = items.select {|i| i.type_id == 10}.last

Leave off the .last if you decide you want all matches:

matching_items = items.select {|i| i.type_id == 10}

Upvotes: 1

Related Questions