Skip to content
Related Articles
Open in App
Not now

Related Articles

Ruby | Enumerator::new function

Improve Article
Save Article
Like Article
  • Last Updated : 06 Jan, 2020
Improve Article
Save Article
Like Article

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
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!