I am scanning for an element in source
that satisfies a condition. The condition is often, but not always, a regexp match. I'm looking for a version of find
that returns the result of the condition, not the original element. With find
, I have to re-compute the criterion for the successful element.
The best I worked out runs along this line:
source.find {|e| if (m = e.match(/(e.)/)); break m[0]; end}
To avoid semicolons prompting Rubocop to complain about multi-statement lines, I prefer to write as follows:
source.find {|e| break m[0] if (m = e.match(/(e.)/))}
But Ruby can't cope with the forward reference (and I'm not twisted enough to re-use e
for m
).
Is there something more elegant to do this job with the short-cutting?
Since you have break
, you don't need find
to break. Use each
.
source.each {|e| m = e[/e./] and break m}