如何让我的代码记住当前位置并下次显示下一个元素?
在Python中,有这样使用的iter()
:
>>> 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
>>>
Ruby有同样的功能吗?
我尝试了这个,但似乎存在一个问题:
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>
为什么 Ruby 找不到 a
变量?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ruby 也有迭代器。
基本用途是:
您可以在方法中使用它:
您的 Ruby 代码失败,因为
a
不在范围内,换句话说,Ruby 在内部看不到a
b
方法。它的典型定义方式如我上面所示。所以,你的代码很接近。另外,请注意,我们很少在 Ruby 中编写 for/循环。有一些原因,例如
for
循环在运行后留下局部变量,并且如果循环定义不正确,则可能会超出数组末尾(例如,如果您正在创建一个索引)访问数组的各个元素。相反,我们使用 .each 迭代器依次返回每个元素,这样就不可能超出末尾,并且不会留下局部变量。Ruby has iterators also.
The basic use is:
You can use that in a method:
Your Ruby code is failing because
a
is not in scope, in other words, Ruby doesn't seea
inside theb
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.使用您提供的代码,并假设您希望打印出这些值:(
有更好的方法,如 马克·托马斯指出)
Working with the code which you provided, and assuming that you want the values to be printed out:
(There are much better ways, as Mark Thomas pointed out)