如何在 ruby、block、for、each、do 中跟踪计数器变量
我忘记了如何跟踪 Ruby 中循环的位置。通常我用 JavaScript、AS3、Java 等编写。
each
:
counter = 0
Word.each do |word,x|
counter += 1
#do stuff
end
for
:
same thing
while
:
same thing
block
Word.each {|w,x| }
这个我真的不知道。
I forget how to keep track of the position of the loops in Ruby. Usually I write in JavaScript, AS3, Java, etc.
each
:
counter = 0
Word.each do |word,x|
counter += 1
#do stuff
end
for
:
same thing
while
:
same thing
block
Word.each {|w,x| }
This one I really don't know about.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用
each_with_index
而不是each
,您将获得索引和元素。所以你可以这样做:对于
while
循环,你仍然需要自己跟踪计数器。If you use
each_with_index
instead ofeach
, you'll get an index along with the element. So you can do:For
while
loops you'll still have to keep track of the counter yourself.大写的 W 意味着它是一个常量,这很可能意味着它是一个类或模块而不是类的实例。我猜你可以让一个类使用 every 返回一个可枚举的值,但这看起来很奇怪。
为了删除令人困惑的额外垃圾和可能的大写错误的示例,我将使我的代码如下所示。
我不确定 Sepp2K 对这个奇怪的 (word,x) 东西做了什么。
A capital W would mean it's a constant which most likely mean it's a class or a module not an instance of a class. I guess you could have a class return an enumerable using each but that seems very bizarre.
To remove the confusing extra junk and the, possibly, incorrectly capitalized example I would make my code look like this.
I'm not sure what Sepp2K was doing with the weird (word,x) thing.
除了 Ruby 1.8 的 Array#each_with_index 方法之外,Ruby 1.9 中的许多枚举方法在没有块的情况下调用时都会返回 Enumerator;然后,您可以调用
with_index
方法让枚举器也传递索引:如果您想要
map.with_index
或select.with_index
(或等)在 Ruby 1.8.x 下,您可以执行这种无聊但快速的方法:或者您可以获得更多功能乐趣:
In addition to Ruby 1.8's
Array#each_with_index
method, many enumerating methods in Ruby 1.9 return an Enumerator when called without a block; you can then call thewith_index
method to have the enumerator also pass along the index:If you want
map.with_index
orselect.with_index
(or the like) under Ruby 1.8.x, you can either do this boring-but-fast method:or you can have more functional fun: