我有这堂课:
class MyArray
attr_accessor :data
def initialize(my_object = nil)
@data = Array[*my_object]
end
def <<(y)
@data << y
end
def each
@data.each
end
end
我正在使用它
subject = MyArray.new([2, 5, 3]) d = [] subject.each { |i| d << i }
问题是,它不会通过-subject.each-迭代一次。我该怎么做才能从数组中返回“each”值作为方法返回值?如何返回迭代器本身?
我试过这个并且它也不起作用:
def each [2,5,3].each end
感谢“meagar”和“Erik Allik”,我们有正确的答案:(只有“def each”方法已经改变)
class MyArray
attr_accessor :data
def initialize(my_object = nil)
@data = Array[*my_object]
end
def <<(y)
@data << y
end
def each(&block)
@data.each(&block)
end
end
答案 0 :(得分:4)
问题是each {block}
实际上是在数组上调用each
而传递方法的块参数。您的块参数被忽略。
如果您希望这项工作正常,您需要将该块转发到嵌套的each
电话中:
class Test
def each(&block)
[1, 2, 3].each(&block)
end
end
Test.new.each do |i|
puts i
end
如果要返回迭代器,可以自由地执行此操作,但是必须在该迭代器上调用each
,然后提供 块:
class Test
def each
[1, 2, 3].each
end
end
Test.new.each.each do |i|
puts i
end
答案 1 :(得分:1)
您需要将传递给自定义def each
的广告块传递给实际的未明确each
:
def each(&block) # take the block passed to each as a Proc object
@data.each(&block) # pass the Proc on as a block to the underlying each
end
相当于:
def each
# just create a new block that calls the passed in block
# without creating an intermediate Proc object
@data.each { |i| yield i }
end