1

我有这门课:

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- 迭代一次。我应该怎么做才能从数组中返回“每个”值作为方法返回值?如何返回迭代器本身?

我试过了,它也不起作用:

  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
4

2 回答 2

5

问题是实际上是在数组上each {block}调用并将块参数传递给方法。您的 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
于 2013-10-07T14:01:39.483 回答
1

您需要将传递给自定义的块传递给def each实际的 underlyign 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
于 2013-10-07T14:02:10.543 回答