What is the Ruby equivalent of Python's iter()/next()?

558 Views Asked by At

In python I can get an iterator from any iterable with iter(); and then I can call next(my_iter) to get the next element.

Is there any equivalent in ruby/rails?

3

There are 3 best solutions below

4
Rajagopalan On BEST ANSWER

.to_enum will yield the enumerator. For an example a.to_enum will yield the enumerator and you can iterate it from there like a.to_enum.each{|x| p x}.

Or without loop, you can take the element like

p a.to_enum.next
1
spike 王建 On

There are many iterators in Ruby as follows:

  1. Each Iterator
  2. Collect Iterator
  3. Times Iterator
  4. Upto Iterator
  5. Downto Iterator
  6. Step Iterator
  7. Each_Line Iterator
  8. Explaining Types of Iterators

Each Iterator: This iterator returns all the elements of an array or a hash. Each iterator returns each value one by one. Syntax:

collection.each do |variable_name|
   # code to be iterate
   continue if condition # equivalent next in python 
end

In the above syntax, the collection can be the range, array or hash.

referenced from https://www.geeksforgeeks.org/ruby-types-of-iterators/

0
nullTerminator On

Without a loop:

words = %w(one two three four five)

my_iter = words.each

puts my_iter.next  # one
puts my_iter.next  # two

But what is the point of an iterator that isn't in a loop? It's kind of the whole raison d'etre of them...