The scenario looks something like this: you have an input that you want to process using one of several possible processes, depending on the quality of the input itself. You do not know in advance what will work until you try to send an input for everyone.
Let's say you have many possible attempts to try. You want to find the first proc that does not cause an error and get its return value, preferably in one pass. And if proc is not found, throw an error.
What is the best way to do this in ruby?
My answer so far looks like one of the two below, but I'm looking for a more idiomatic path. And also a way that treats the nil return value as real - right now both of them treat nil as an error state.
(1)
ret = nil array_of_procs.find do |p| begin ret = p[input] rescue next end end raise ArgumentError unless ret
(2)
ret = array_of_procs.inject(nil) do |memo, p| memo = p[input] rescue next break memo end raise ArgumentError unless ret
source share