Cbb09ca8a832170ec73186f5c8cafba4

What is the best way to emulate Python's enumerate in Ruby?

Here is what it looks like in Python:

for i,j in enumerate(['foo', 'bar', 'baz']):
print i,j

But Ruby requires twice as many lines in order to do the same thing:

i = 0
for j in ['foo', 'bar', 'baz']
puts "#{i} #{j}"
i += 1
end

Is there a better way?

1
2
3
4
5
i = 0
for j in ['foo', 'bar', 'baz']
    puts "#{i} #{j}"
    i += 1
end

Refactorings

No refactoring yet !

Be1e3ee645d23c95ba650c21bc885927

Fabien Jakimowicz

July 14, 2008, July 14, 2008 23:23, permalink

4 ratings. Login to rate!
1
['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
8f6f95c4bd64d5f10dfddfdcd03c19d6

Rick DeNatale

July 14, 2008, July 14, 2008 23:46, permalink

3 ratings. Login to rate!

Easy.

1
['foo', 'bar', 'baz'].each_with_index {|element, index| puts "#{i} #{j}"}
Cbb09ca8a832170ec73186f5c8cafba4

robby86533.identity.net

July 15, 2008, July 15, 2008 00:02, permalink

No rating. Login to rate!

each_with_index -- that is the key. Two points for refactormycode--thanks! (although the Ruby .each* syntax always seems backwards to me...)

Your refactoring





Format Copy from initial code

or Cancel