Ruby 1.9枚举更改

Ruby 1.9枚举更改,ruby,ruby-1.9,Ruby,Ruby 1.9,所以,我不太了解Ruby 1.9对枚举数的更改,但我想要的是对集合进行惰性筛选/映射,例如,如何创建一个与此等效的惰性枚举数 (1..100).find_all{|x| x % 2 == 1}.map{|x| x * 2}.find_all{|x| x % 3 == 0} 我尝试将lambda传递给#enum_for,但它在我的机器上不起作用。您可以找到lazy_select和lazy_map的实现。您只需通过这两种方法扩展枚举器模块。那么你应该可以使用 (1..100).lazy_sele

所以,我不太了解Ruby 1.9对枚举数的更改,但我想要的是对集合进行惰性筛选/映射,例如,如何创建一个与此等效的惰性枚举数

(1..100).find_all{|x| x % 2 == 1}.map{|x| x * 2}.find_all{|x| x % 3 == 0}

我尝试将lambda传递给#enum_for,但它在我的机器上不起作用。

您可以找到lazy_select和lazy_map的实现。您只需通过这两种方法扩展枚举器模块。那么你应该可以使用

 (1..100).lazy_select{|x| x % 2 == 1}.lazy_map{|x| x * 2}.lazy_select{|x| x % 3 == 0}

遗憾的是,您无法使用enum_来执行此操作。对于惰性可枚举项,必须使用如下内容:

class LazyEnum
  include Enumerable

  attr_accessor :enum, :operations

  def initialize enum
    @enum = enum
    @operations = []
  end

  def each
    enum.each do |x|
      filtered = false
      operations.each do |type, op|
        if type == :filter
          unless op[x]
            filtered = true
            break
          end
        else
          x = op[x]
        end
      end
      yield x unless filtered
    end
  end

  def map! &blk
    @operations << [:transform, blk]
    self
  end

  def select! &blk
    @operations << [:filter, blk]
    self
  end

  def reject!
    select! {|x| !(yield x)}
  end

  def dup
    LazyEnum.new self
  end

  def map &blk
    dup.map! &blk
  end

  def select &blk
    dup.select! &blk
  end

  def reject &blk
    dup.reject! &blk
  end
end

LazyEnum.new(1..100).select{|x| x % 2 == 1}.map{|x| x * 2}.select{|x| x % 3 == 0}
#=> #<LazyEnum:0x7f7e11582000 @enum=#<LazyEnum:0x7f7e115820a0 @enum=#<LazyEnum:0x7f7e11582140 @enum=#<LazyEnum:0x7f7e115822d0 @enum=1..100, @operations=[]>, @operations=[[:filter, #<Proc:0x00007f7e11584058@(irb):348>]]>, @operations=[[:transform, #<Proc:0x00007f7e11583a90@(irb):348>]]>, @operations=[[:filter, #<Proc:0x00007f7e115823c0@(irb):348>]]>
irb(main):349:0> LazyEnum.new(1..100).select{|x| x % 2 == 1}.map{|x| x * 2}.select{|x| x % 3 == 0}.to_a
#=> [6, 18, 30, 42, 54, 66, 78, 90, 102, 114, 126, 138, 150, 162, 174, 186, 198]
类懒虫
包括可枚举的
属性访问器:枚举,:操作
def初始化枚举
@枚举=枚举
@操作=[]
结束
定义每个
枚举每个do | x|
过滤=假
操作。每个do类型,op|
如果类型==:过滤器
除非op[x]
过滤=真
打破
结束
其他的
x=op[x]
结束
结束
除非过滤,否则产量为x
结束
结束
def地图&黑色
@操作LazyEnum.new(1..100)。选择{x | x%2==1}。映射{x | x*2}。选择{x | x%3==0}。到
#=> [6, 18, 30, 42, 54, 66, 78, 90, 102, 114, 126, 138, 150, 162, 174, 186, 198]