Home > Back-end >  Rails- is there a method that is essentially `map.find` for arrays?
Rails- is there a method that is essentially `map.find` for arrays?

Time:07-19

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.

CodePudding user response:

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
  • Related