2

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?

0

3 Answers 3

5

Try:

matching_item = items.reverse.find{ |i| i.type_id == 10 } 
Sign up to request clarification or add additional context in comments.

Comments

1

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} 

1 Comment

There are nice, though they search all the array and don't stop when the find the fitst matching element. Any way to to this?
1
items.reverse_each.detect{|item| iterm.type_id == 10} #or items[items.rindex{|item| item.type_id == 10}] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.