Ruby | Enumerator::new function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

[2, 2, 4, 8]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.