Automatic counter in Ruby for each?

前端 未结 8 1261
孤街浪徒
孤街浪徒 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}
    
    0 讨论(0)
  • 2020-11-29 23:12

    The enumerating enumerable series is pretty nice.

    0 讨论(0)
  • 2020-11-29 23:20
    [:a, :b, :c].each_with_index do |item, i|
      puts "index: #{i}, item: #{item}"
    end
    

    You can't do this with for. I usually like the more declarative call to each personally anyway. Partly because its easy to transition to other forms when you hits the limit of the for syntax.

    0 讨论(0)
  • 2020-11-29 23:23

    If you don't have the new version of each_with_index, you can use the zip method to pair indexes with elements:

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

    which produces:

    1 one
    2 two
    3 three
    4 four
    5 five
    
    0 讨论(0)
  • 2020-11-29 23:27

    As to your question about doing i++, well, you cannot do that in Ruby. The i += 1 statement you had is exactly how you're supposed to do it.

    0 讨论(0)
  • 2020-11-29 23:27

    If blahs is a class that mixes in Enumerable, you should be able to do this:

    blahs.each_with_index do |blah, i|
      puts("#{i} #{blah}")
    end
    
    0 讨论(0)
提交回复
热议问题