Automatic counter in Ruby for each?
- by yar
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.