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?

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!
['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.

['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...)

D264e9dd3768e50e27aa3364cdfe3b6d

panzi

November 13, 2010, November 13, 2010 16:09, permalink

No rating. Login to rate!

Isn't there something like collect_with_index? This _with_index seems pretty inflexible to me. Even though I like Rubys closures I think Pythons generator functions are much more powerful.

Your refactoring





Format Copy from initial code

or Cancel