0

In Python there is iter() used like this:

>>> a=[1,2,4]
>>> b=iter(a)
>>> b.next()
1
>>> b.next()
2
>>> b.next()
4
>>> b.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

Does Ruby have the same feature?

I tried this but it seems there is an issue:

ruby-1.9.2-p0 > a=[1,2,3]
 => [1, 2, 3] 
ruby-1.9.2-p0 > def b()
ruby-1.9.2-p0 ?>  for i in a
ruby-1.9.2-p0 ?>    yield i
ruby-1.9.2-p0 ?>    end
ruby-1.9.2-p0 ?>  end
 => nil 
ruby-1.9.2-p0 > b
NameError: undefined local variable or method `a' for #<Object:0xb7878950>

Why didn't Ruby find the a variable?

martineau
  • 119,623
  • 25
  • 170
  • 301
mlzboy
  • 14,343
  • 23
  • 76
  • 97

3 Answers3

2

Ruby has iterators also.

The basic use is:

>> iter = [0,1,2,3].each #=> #<Enumerator: [0, 1, 2, 3]:each>
>> iter.next #=> 0
>> iter.next #=> 1
>> iter.next #=> 2
>> iter.next #=> 3
>> iter.next
StopIteration: iteration reached an end
        from (irb):6:in `next'
        from (irb):6
        from /Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/irb:16:in `<main>'
>>

You can use that in a method:

def iter(ary)
  ary.each do |i|
    yield i
  end
end

iter([1,2,3]) { |i| puts i}
# >> 1
# >> 2
# >> 3

Your Ruby code is failing because a is not in scope, in other words, Ruby doesn't see a inside the b method. The typical way it would be defined is as I show it above. So, your code is close.

Also, note that we seldom write a for/loop in Ruby. There are reasons such as for loops leaving a local variable behind after running, and potential for running off the end of an array if the loop isn't defined correctly, such as if you are creating an index to access individual elements of an array. Instead we use the .each iterator to return each element in turn, making it impossible to go off the end, and not leaving a local variable behind.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
1

Working with the code which you provided, and assuming that you want the values to be printed out:


a = [1, 2, 3]
def b(a)
  a.each { |i| puts i }
end
b(a)

(There are much better ways, as Mark Thomas pointed out)

Community
  • 1
  • 1
Sujith Surendranathan
  • 2,569
  • 17
  • 21
1
[1,2,4].each { |i| puts i }
Dave Rapin
  • 1,471
  • 14
  • 18
  • that doesn't answer the question which is how to do an "external" iterator in Ruby. not how to do a loop. – mb14 Nov 22 '10 at 11:53