Open In App

Ruby | Enumerator::new function

Last Updated : 06 Jan, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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
# 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
# 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]

Next Article

Similar Reads