Automatic counter in Ruby for each?

前端 未结 8 1262
孤街浪徒
孤街浪徒 2020-11-29 23:02

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

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

Is there a better way to do it?

相关标签:
8条回答
  • 2020-11-29 23:29

    If you want to get index of ruby for each, then you can use

    .each_with_index
    

    Here is an example to show how .each_with_index works:

    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
    

    This will print:

    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
    
    0 讨论(0)
  • 2020-11-29 23:30

    As people have said, you can use

    each_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) }
    

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

    0 讨论(0)
提交回复
热议问题