mshsayem
mshsayem

Reputation: 18018

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

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?

Upvotes: 2

Views: 626

Answers (3)

nullTerminator
nullTerminator

Reputation: 396

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

Upvotes: 1

Rajagopalan
Rajagopalan

Reputation: 6064

.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

Upvotes: 6

spike 王建
spike 王建

Reputation: 1714

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/

Upvotes: 0

Related Questions