将几个Enumerable变成一个

时间:2018-09-01 05:05:38

标签: ruby enumerable

是否有一种方法可以将多个Enumerable对象显示为单个Enumerable,而无需将其展平为Array?目前,我已经编写了这样的课程,但我觉得必须有一个内置的解决方案。

class Enumerables
  include Enumerable

  def initialize
    @enums = []
  end

  def <<(enum)
    @enums << enum
  end

  def each(&block)
    if block_given?
      @enums.each { |enum|
        puts "Enumerating #{enum}"
        enum.each(&block)
      }
    else
      to_enum(:each)
    end
  end
end

enums = Enumerables.new
enums << 1.upto(3)
enums << 5.upto(8)
enums.each { |s| puts s }

作为一个简单的示例,它需要能够接受像这样的无限枚举器。

inf = Enumerator.new { |y| a = 1; loop { y << a; a +=1 } };

3 个答案:

答案 0 :(得分:4)

好吧,这可以通过使用Enumerator的标准库来完成。这种方法的优势在于它会返回 real 枚举器,该枚举器可能会被映射,缩减等。

element.innerHTML = `<%@include file="../jsp/welcome.jsp" %>`;

答案 1 :(得分:2)

毕竟。对元素使用Enumerable::Lazy#flat_map.each.lazy

inf = Enumerator.new { |y| a = 1; loop { y << a; a += 1 } }
[(1..3).to_a, inf].lazy.flat_map { |e| e.each.lazy }.take(10).force
#⇒ [1, 2, 3, 1, 2, 3, 4, 5, 6, 7]

答案 2 :(得分:0)

我最终得到了这种解决方案,也许与您已经尝试过的解决方案很接近:

def enumerate(*enum)
  enum.each_with_object([]) { |e, arr| arr << e.to_a }.flatten
end

enumerate( 1..3, 5.upto(8), 3.times, 'a'..'c' ).each { |e| p e }

# => 1, 2, 3, 5, 6, 7, 8, 0, 1, 2, "a", "b", "c"

或者(相同的力学):

def enumerate(*enum)
  enum.flat_map { |e| e.to_a }
end
相关问题