Python's enumerate in Ruby?
Something like this in Python:
a = ['do', 're', 'mi', 'fa']
for i, s in enumerate(a):
print('%s at index %d' % (s, i))
becomes this in Ruby:
a = %w(do re mi fa)
a.each_with_index do |s,i|
puts "#{s} at index #{i}"
end
Assuming it's for enumeration, each_with_index
can do that. Or if you have an Enumerator
, just use with_index
.
Maybe a quicker solution would be :
%w(a b c).map.with_index {|x, i| [i, x] }