How to access the parent collection in a each closure?

主宰稳场 提交于 2020-01-06 19:53:47

问题


I'm looking from something that to replace the *parent*.

%w[apple apples].each do |w|
   next if *parent*.includes? w + "s"
   puts w
end

# output: apples

回答1:


each is a convention, there is no concept of a "parent collection" for blocks in general or ones passed to each in particular. Just name it, eg

(parent = %w[apple apples]).each do |w|
  next if parent.includes? w + "s"
  puts w
end

You could add a different method to pass a parent,

eg

module Each2
 def each2
   each { |elem| yield(self, elem) }
 end
end

include Each2

%w[apple apples].each2 do |parent, w|
  next if parent.includes? w + "s"
  puts w
end

But this is pretty silly.




回答2:


There's no way to do that. You'll have to give the collection a name first:

fruits = %w[apple apples]
fruits.each do |w|
   next if fruits.includes? w + "s"
   puts w
end


来源:https://stackoverflow.com/questions/3695789/how-to-access-the-parent-collection-in-a-each-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!