如何使我的枚举器接口接受Feed?

问题描述 投票:7回答:2

来自docs for Ruby v2.5

e = [1,2,3].map
p e.next           #=> 1
e.feed "a"
p e.next           #=> 2
e.feed "b"
p e.next           #=> 3
e.feed "c"
begin
  e.next
rescue StopIteration
  p $!.result      #=> ["a", "b", "c"]
end

但是当我通过Enumerator.new创建我的枚举时呢?

# a naive rework of the above enum
e2 = Enumerator.new do |y|
  [1,2,3].each do |x|
    y << x
  end
  # raise StopIteration, FED # <= how to get `FED`?
end

p e2.next           #=> 1
e2.feed "a"
p e2.next           #=> 2
e2.feed "b"
p e2.next           #=> 3
e2.feed "c"
begin
  e2.next
rescue StopIteration
  p $!.result      #=> nil
end

我如何修改它以匹配API?

我尝试过的事情:

e2 = Enumerator.new do |y|
  [1,2,3].each do |x|
    @fed = yield
    y << x
  end
  raise StopIteration, @fed
end

e2 = Enumerator.new do |y|
  [1,2,3].each do |x|
    y << yield(x)
  end
  raise StopIteration, y
end

e2 = Enumerator.new do |y|
  enum = [1,2,3].each{|x| yield x }.to_enum
  y << enum.next
  raise StopIteration, y
end

有趣的是,当第二次调用feed时,它们都会产生相同的错误:

# Ignoring all the other errors that jump up…
p e2.next           #=> 1
e2.feed "a"
# nil
p e2.next           #=> 2
e2.feed "b"

TypeError:已设置的Feed值

TypeError:已设置的feed值意味着它正在某处收集值,我只是不知道如何访问它。

#feed的C源代码:

static VALUE
enumerator_feed(VALUE obj, VALUE v)
{
    struct enumerator *e = enumerator_ptr(obj);

    if (e->feedvalue != Qundef) {
        rb_raise(rb_eTypeError, "feed value already set");
    }
    e->feedvalue = v;

    return Qnil;
}

所以feedvalue是我的目标。我已经使用Pry进入了该方法的操作,但找不到与feedfeedvalue相关的方法或变量。 Rubinius makes this available explicitly(至少作为实例变量)。

我很难过。

任何帮助或见解将不胜感激。

ruby
2个回答
1
投票

您的第一个示例是枚举器,其yield方法为:map

e = [1,2,3].map
=> #<Enumerator: [1, 2, 3]:map>

你的第二个例子是一个:each的yield方法的枚举器。

e2 = Enumerator.new do |y|
  [1,2,3].each do |x|
    y << x
  end
  # raise StopIteration, FED # <= how to get `FED`?
end
=> #<Enumerator: #<Enumerator::Generator:0x007fa69b056b50>:each> 

你应该使用to_enumenum_for和你选择的yield方法:

[1,2,3].to_enum(:map)
=> #<Enumerator: [1, 2, 3]:map>

现在不推荐使用以下方式使用::new,因此我不建议使用它来支持提供相同功能的to_enumenum_for

Enumerator.new([1,2,3], :map)

摘要

总结一下,#map是你的第一个迭代器调用的方法,当它是called时,它的return values将决定结果的值。当像你的其他例子一样使用#each时,你对块(#feed)的结束并不重要,因为它不会影响#each的返回值。


3
投票

你的第一个例子以它的方式工作的原因是因为你使用#map“将数组的元素传递给”yield“并将”yield“的结果收集为数组。”在Enumerator#feed http://ruby-doc.org/core-2.5.0/Enumerator.html#method-i-feed中有一个有趣的说明

无论如何,如果您还在其上调用map,您的自定义枚举器的行为将与第一个示例中的Array相同:

e2 = Enumerator.new { |y|
  [1,2,3].each do |x|
    y << x
  end
}.map

p e2.next           #=> 1
e2.feed "a"
p e2.next           #=> 2
e2.feed "b"
p e2.next           #=> 3
e2.feed "c"
begin
  e2.next
rescue StopIteration
  p $!.result      #=> ["a", "b", "c"]
end
© www.soinside.com 2019 - 2024. All rights reserved.