Automatic counter in Ruby for each?

前端 未结 8 1298
孤街浪徒
孤街浪徒 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
    

提交回复
热议问题