
Issue #8421 has been updated by alexbarret (Alexandre Barret). zverok (Victor Shepelev) wrote in #note-4:
@alexbarret There is a somewhat lesser-known trick which looks pretty close to your code: ```ruby # proposal: find_map(emails) do |email| (matches = pattern.match(email)) && matches[:identifier] end # a "trick" emails.find { |email| match = pattern.match(email) and break match[:identifier] } # => "thecode" ``` It might even be considered two tricks, depending on your point of view: the control-flow `and` allows to chain any statements to it (note it doesn't need extra parentheses after assignment), and `break value` allows to return a non-standard value from a block.
Not saying it is beautiful, just one more option.
Thanks I learned something, and it makes sense thinking about it. Both `and` and `break` aren't things I'm used to use in Ruby code but I'm glad I know this trick. Not sure I'll use it much. Breaking with another value than the expected value returned from the enumerable method can be confusing. ---------------------------------------- Feature #8421: add Enumerable#find_map and Enumerable#find_all_map https://bugs.ruby-lang.org/issues/8421#change-107330 * Author: Hanmac (Hans Mackowiak) * Status: Feedback ---------------------------------------- currently if you have an Enumerable and you want to return the return value of #find you need eigther: (o = enum.find(block) && block.call(o)) || nil or enum.inject(nil) {|ret,el| ret || block.call(el)} neigher of them may be better than an directly maked method same for #find_all_map enum.lazy.map(&:block).find_all{|el| el} it may work but it is not so good -- https://bugs.ruby-lang.org/