mlzboy
mlzboy

Reputation: 14721

How do I make my code remember the current position and next time show the next element?

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?

Upvotes: 0

Views: 240

Answers (3)

the Tin Man
the Tin Man

Reputation: 160621

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.

Upvotes: 2

Dave Rapin
Dave Rapin

Reputation: 1481

[1,2,4].each { |i| puts i }

Upvotes: 1

Sujith Surendranathan
Sujith Surendranathan

Reputation: 2579

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)

Upvotes: 1

Related Questions