Automatic counter in Ruby for each?

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

    Yes, it's collection.each to do loops, and then each_with_index to get the index.

    You probably ought to read a Ruby book because this is fundamental Ruby and if you don't know it, you're going to be in big trouble (try: http://poignantguide.net/ruby/).

    Taken from the Ruby source code:

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

提交回复
热议问题