Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Ruby | Enumerator::new function

  • Last Updated : 06 Jan, 2020

The new function in Ruby is used to create a new Enumerator object, which can be used as an Enumerable.

Syntax: Enumerator.new
Here, Enumerator is an object.

Parameters: This function does not accept any parameters.

Returns: the new set of values.

Example 1:






# Ruby program for Enumerator::new function
  
# Calling the new function
fib = Enumerator.new do |y|
  a = b = 2
  loop do
    y << a
    a, b = b, a + b
  end
end
   
# Getting the result in an array form
p fib.take(10

Output:

[2, 2, 4, 6, 10, 16, 26, 42, 68, 110]

Example 2:




# Ruby program for Enumerator::new function
   
# Calling the new function
fib = Enumerator.new do |y|
  a = b = 2
  loop do
    y << a
    a, b = b, a * b
  end
end
   
# Getting the result in an array form
p fib.take(4

Output:

[2, 2, 4, 8]
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!