new

Enumerator.new(size = nil) { |yielder| ... }
Enumerator.new(obj, method = :each, *args)
Class Public methods

Creates a new Enumerator object, which can be used as an Enumerable.

In the first form, iteration is defined by the given block, in which a âyielderâ object, given as block parameter, can be used to yield a value by calling the yield method (aliased as +<<+):

fib = Enumerator.new do |y|
  a = b = 1
  loop do
    y << a
    a, b = b, a + b
  end
end

p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

The optional parameter can be used to specify how to calculate the size in a lazy fashion (see #size). It can either be a value or a callable object.

In the second, deprecated, form, a generated Enumerator iterates over the given object using the given method with the given arguments passed.

Use of this form is discouraged. Use Kernel#enum_for or Kernel#to_enum instead.

e = Enumerator.new(ObjectSpace, :each_object)
    #-> ObjectSpace.enum_for(:each_object)

e.select { |obj| obj.is_a?(Class) }  #=> array of all classes
doc_ruby_on_rails
2015-04-05 04:37:29
Comments
Leave a Comment

Please login to continue.