关于语法:Ruby中的每个自动计数器?

Automatic counter in Ruby for each?

我想使用for-for和counter:

1
2
3
4
5
i=0
for blah in blahs
    puts i.to_s +"" + blah
    i+=1
end

有更好的方法吗?

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

从技术上讲,Matt和Squeegy的答案排在第一位,但是我给paradoja最好的答案,所以在SO上的要点分散了一些。 他的答案也有关于版本的注释,该注释仍然有意义(只要我的Ubuntu 8.04使用Ruby 1.8.6)。

应该使用puts"#{i} #{blah}"更加简洁。


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

1
each_with_index

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

1
2
3
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中执行此操作。


1
2
3
[:a, :b, :c].each_with_index do |item, i|
  puts"index: #{i}, item: #{item}"
end

您不能使用for。无论如何,我通常都喜欢对每个人进行更具声明性的通话。部分原因是当您达到for语法的限制时,它易于转换为其他形式。


是的,collection.each进行循环,然后each_with_index进行索引。

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

取自Ruby源代码:

1
2
3
4
5
 hash = Hash.new
 %w(cat dog wombat).each_with_index {|item, index|
   hash[item] = index
 }
 hash   #=> {"cat"=>0,"wombat"=>2,"dog"=>1}


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

1
2
blahs = %w{one two three four five}
puts (1..blahs.length).zip(blahs).map{|pair|'%s %s' % pair}

产生:

1
2
3
4
5
1 one
2 two
3 three
4 four
5 five


关于执行i++的问题,那么您不能在Ruby中执行。您拥有的i += 1语句正是您应该做的。


可枚举的系列非常好。


如果要获取每个的红宝石指数,则可以使用

1
.each_with_index

这是显示.each_with_index如何工作的示例:

1
2
3
4
5
6
7
8
range = ('a'..'z').to_a
length = range.length - 1
range.each_with_index do |letter, index|
    print letter +""
    if index == length
        puts"You are at last item"
    end
end

这将打印:

1
a b c d e f g h i j k l m n o p q r s t u v w x y z You are at last item

如果blahs是在Enumerable中混合使用的类,则您应该能够做到这一点:

1
2
3
blahs.each_with_index do |blah, i|
  puts("#{i} #{blah}")
end