0

Looking for a method that will iterate through a list and return the first transformed value. Essentially:

[1, 2, 3, 4].magic { |i| puts "Checking #{i}" i ** 2 if i > 2 } Checking 1 Checking 2 Checking 3 #=> 9 

The goal here being that it works like find and stops iterating through the list after getting the first return. (Notice it never checks 4) but also returns the value from the block. (Returns 9 instead of 3)

The issue here is that the block is performing some complex logic, so I don't want to map over the entire array, but I also want to use the value of said logic.

1 Answer 1

1

You can break the loop with a desired return value. Is this what you are looking for?

array = [1, 2, 3, 4] array.map { |element| break element ** 2 if element > 2 } # returns 9 
Sign up to request clarification or add additional context in comments.

2 Comments

Not quite as elegant as I was hoping, and you need special functionality to handle no matched, but essentially does what I need! Thank you!
You can map the array with the result object if you want. This way it will return the result object if it is not break. This way you may return a default value if there is no match but still it won't be elegant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.