Ruby 如何创建枚举器包装类?

Ruby 如何创建枚举器包装类?,ruby,Ruby,我有这个功能: def file_parser (filename) Enumerator.new do |yielder| File.open(filename, "r:ISO-8859-1") do |file| csv = CSV.new(file, :col_sep => "\t", :headers => true, :quote_char => "\x07") csv.eac

我有这个功能:

def file_parser (filename)
  Enumerator.new do |yielder|
    File.open(filename, "r:ISO-8859-1") do |file|
      csv = CSV.new(file, :col_sep => "\t", :headers => true, :quote_char => "\x07")                            
      csv.each do |row|
        yielder.yield map_fields(clean_data(row.to_hash))
      end
    end
  end
end
我可以这样使用它:

parser = file_parser("data.tab")
parser.each do { |data| do_profitable_things_with data }
parser = SpecialParser.new("data.tab")
parser.each do { |data| do_profitable_things_with data }
class SpecialParser
  include Enumerable  # needed to provide the other Enumerable methods

  def initialize(filename)
    @filename = filename
    @enum = file_parser(filename)
  end

  def each
    @enum.each do |val|
      yield val
    end
  end
end
相反,我想把它放在自己的类中,并像这样使用它:

parser = file_parser("data.tab")
parser.each do { |data| do_profitable_things_with data }
parser = SpecialParser.new("data.tab")
parser.each do { |data| do_profitable_things_with data }
class SpecialParser
  include Enumerable  # needed to provide the other Enumerable methods

  def initialize(filename)
    @filename = filename
    @enum = file_parser(filename)
  end

  def each
    @enum.each do |val|
      yield val
    end
  end
end
我尝试了一些我不希望起作用的事情,比如从
initialize()
返回枚举数,以及
self=file\u parser()

我也试过
super-do | yielder |


出于某种原因,我没有想到这样做的方法。

SpecialParser
中使
file\u解析器成为私有方法

然后像这样设置班上的其他人:

parser = file_parser("data.tab")
parser.each do { |data| do_profitable_things_with data }
parser = SpecialParser.new("data.tab")
parser.each do { |data| do_profitable_things_with data }
class SpecialParser
  include Enumerable  # needed to provide the other Enumerable methods

  def initialize(filename)
    @filename = filename
    @enum = file_parser(filename)
  end

  def each
    @enum.each do |val|
      yield val
    end
  end
end
编辑:


如果您想免费使用另一个可枚举方法,还必须在类中包含可枚举的
函数。

您只需在类中包含可枚举的
模块,并定义一个调用
yield
函数

您仍然可以免费获得所有可枚举的
方法,如
map
reduce

class SpecialParser
  include Enumerable

  def initialize(n)
    @n = n
  end

  def each
    0.upto(@n) { |i| yield i }
  end
end

sp = SpecialParser.new 4
sp.each { |i| p i }
p sp.map { |i| i }
输出:

0
1
2
3
4
[0, 1, 2, 3, 4]

那么,如果有人想用_index
next
或他们期望从枚举器中得到的其他方法来做每个_,会发生什么呢?我必须定义每个方法。@ShawnJ.Goff好的,编辑。我有点困惑,因为你只是建议它应该像标题中的
可枚举的
。没有读过这些,我以为你只想要
每个
方法。