Reputation: 31
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
Reputation: 80065
items.reverse_each.detect{|item| iterm.type_id == 10}
#or
items[items.rindex{|item| item.type_id == 10}]
Upvotes: 1
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