Reputation: 18018
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
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
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
Reputation: 1714
There are many iterators in Ruby as follows:
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