Ruby 块有 shorthand 吗?

Is there a shorthand for Ruby Blocks?

我发现自己对 Ruby 中的以下冗长写作感到恼火:

polys.each { |poly| poly.edges.each {|edge| draw edge.start, edge.end } }

polys是多边形数组,边是多边形返回边数组的方法)

理想情况下,我想将其缩短为这样的内容:

polys.each.edges.each { draw _.start, _.end }

更具体的我想知道:

没有。你能做的最接近的是:

polys.flat_map(&:edges).each { |_| draw _.start, _.end }

flat_map 会将一个数组转换为另一个数组,并将其展平为一维数组。如果块内部正在调用不带参数的单个方法,则可以使用 &:edges 快捷方式。

话虽这么说,但我可能会使其更接近您的初始提案,因为它更具可读性:

polys.each do |poly| 
  poly.edges.each {|edge| draw edge.start, edge.end }
end

请记住,您只编写一次代码,但它会被大量阅读,因此可读性胜过简洁性。