How to access the parent collection in a each closure?
I'm looking from something that to replace the *parent*
.
%w[apple apple开发者_运维问答s].each do |w|
next if *parent*.includes? w + "s"
puts w
end
# output: apples
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.
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
精彩评论