2

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?

mshsayem
  • 17,557
  • 11
  • 61
  • 69

3 Answers3

5

.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
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
1

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...

nullTerminator
  • 396
  • 1
  • 6
0

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/

spike 王建
  • 1,556
  • 5
  • 14
  • Well, I was not asking for looping. Each of the examples there actually requires a loop/block/proc to get any element. – mshsayem Aug 31 '20 at 06:40