每个Ruby中的自动计数器?

Dan*_*ark 131 ruby syntax

我想使用for-each和counter:

i=0
for blah in blahs
    puts i.to_s + " " + blah
    i+=1
end
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

注意:我不知道blahs是数组还是哈希,但必须做的blahs[i]不会使它更性感.我也想知道如何i++用Ruby 编写.


从技术上讲,Matt和Squeegy的答案首先出现了,但是我给了paradoja最好的答案,所以在SO上点了几点.他的回答还有关于版本的说明,这仍然是相关的(只要我的Ubuntu 8.04使用Ruby 1.8.6).


应该使用puts "#{i} #{blah}"哪个更简洁.

par*_*oja 189

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

each_with_index
Run Code Online (Sandbox Code Playgroud)

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

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

blahs.map.with_index { |blah, index| something(blah, index) }
Run Code Online (Sandbox Code Playgroud)

这是你可以从ruby 1.8.7和1.9做的事情.

  • 我厌倦了背后的分发,所以我开始使用rvm来管理我在Ubuntu和Linux Mint上的Ruby安装. (3认同)

Ale*_*yne 54

[:a, :b, :c].each_with_index do |item, i|
  puts "index: #{i}, item: #{item}"
end
Run Code Online (Sandbox Code Playgroud)

你不能这样做.无论如何,我通常喜欢对每个人进行更多的声明性调用.部分原因是当您达到for语法的限制时,它很容易转换为其他形式.


Mat*_*ish 10

是的,它是collection.each做循环,然后each_with_index获取索引.

你可能应该读一本Ruby书,因为这是Ruby的基础,如果你不了解它,你将遇到大麻烦(试试:http://poignantguide.net/ruby/).

取自Ruby源代码:

 hash = Hash.new
 %w(cat dog wombat).each_with_index {|item, index|
   hash[item] = index
 }
 hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
Run Code Online (Sandbox Code Playgroud)


Geo*_*rge 6

如果您没有新版本each_with_index,可以使用该zip方法将索引与元素配对:

blahs = %w{one two three four five}
puts (1..blahs.length).zip(blahs).map{|pair|'%s %s' % pair}
Run Code Online (Sandbox Code Playgroud)

产生:

1 one
2 two
3 three
4 four
5 five
Run Code Online (Sandbox Code Playgroud)