Automatic counter in Ruby for each?

Posted by yar on Stack Overflow See other posts from Stack Overflow or by yar
Published on 2009-02-10T19:40:52Z Indexed on 2010/03/14 1:45 UTC
Read the original article Hit count: 381

Filed under:
|

I know you Ruby people will laugh at my bad Ruby code:

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

I want to use a for-each and a counter... is there a better way to do it?

Note: I don't know if blahs is an array or a hash, but having to do blahs[i] wouldn't make it much sexier. Also I'd like to know how to write i++ in Ruby.

Edit: Technically, Matt's and Squeegy's answer came in first, but I'm giving best answer to paradoja so spread around the points a bit on SO. Also his answer had the note about versions, which is still relevant (as long as my Ubuntu 8.04 is using Ruby 1.8.6).

Edit: Should've used puts "#{i} #{blah}" which is a lot more succinct.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about syntax