1 2 3 4 5
i = 0 for j in ['foo', 'bar', 'baz'] puts "#{i} #{j}" i += 1 end
Refactorings
No refactoring yet !
Fabien Jakimowicz
July 14, 2008, July 14, 2008 23:23, permalink
1
['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
Rick DeNatale
July 14, 2008, July 14, 2008 23:46, permalink
Easy.
1
['foo', 'bar', 'baz'].each_with_index {|element, index| puts "#{i} #{j}"}
robby86533.identity.net
July 15, 2008, July 15, 2008 00:02, permalink
each_with_index -- that is the key. Two points for refactormycode--thanks! (although the Ruby .each* syntax always seems backwards to me...)
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?