Ruby 中的自动计数器? [英] Automatic counter in Ruby for each?

查看:52
本文介绍了Ruby 中的自动计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 for-each 和计数器:

I want to use a for-each and a counter:

i=0
for blah in blahs
    puts i.to_s + " " + blah
    i+=1
end

有更好的方法吗?

注意:我不知道 blahs 是一个数组还是一个散列,但必须做 blahs[i] 不会让它更性感.另外我想知道如何在 Ruby 中编写 i++.

Note: I don't know if blahs is an array or a hash, but having to do blahs[i] wouldn't make it much sexier. Also I'd like to know how to write i++ in Ruby.

从技术上讲,Matt 和 Squeegy 的答案是最先出现的,但我对 paradoja 给出了最佳答案,因此在 SO 上稍微散布了要点.他的回答也有关于版本的说明,这仍然是相关的(只要我的 Ubuntu 8.04 使用 Ruby 1.8.6).

Technically, Matt's and Squeegy's answer came in first, but I'm giving best answer to paradoja so spread around the points a bit on SO. Also his answer had the note about versions, which is still relevant (as long as my Ubuntu 8.04 is using Ruby 1.8.6).

应该使用 puts "#{i} #{blah}" 这样更简洁.

Should've used puts "#{i} #{blah}" which is a lot more succinct.

推荐答案

正如人们所说,你可以使用

As people have said, you can use

each_with_index

但是如果您想要索引的迭代器与each"不同(例如,如果您想使用索引或类似的东西进行映射),您可以使用 each_with_index 方法连接枚举器,或者简单地使用 with_index:

but if you want indices with an iterator different to "each" (for example, if you want to map with an index or something like that) you can concatenate enumerators with the each_with_index method, or simply use with_index:

blahs.each_with_index.map { |blah, index| something(blah, index)}

blahs.map.with_index { |blah, index| something(blah, index) }

这是您可以从 ruby​​ 1.8.7 和 1.9 执行的操作.

This is something you can do from ruby 1.8.7 and 1.9.

这篇关于Ruby 中的自动计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆