Python's enumerate in Ruby?
Asked Answered
B

4

27
def enumerate(arr):
    (0..arr.length - 1).to_a.zip(arr)

Is something built in for this? It doesn't need to have it's members immutable, it just needs to be in the standard library. I don't want to be the guy who subclasses the Array class to add a Python feature to a project.

Does it have a different name in Ruby?

%w(a b c).enumerate
=> [[0, "a"], [1, "b"], [2, "c"], [3, "d"]] 
Brink answered 18/12, 2012 at 16:5 Comment(0)
C
37

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
Cheri answered 18/12, 2012 at 16:10 Comment(1)
a = 'do re mi fa'.split() might be closer to the Ruby versionThirzi
E
8

Assuming it's for enumeration, each_with_index can do that. Or if you have an Enumerator, just use with_index.

Eindhoven answered 18/12, 2012 at 16:8 Comment(0)
L
7

Maybe a quicker solution would be :

%w(a b c).map.with_index {|x, i| [i, x] }
Lyle answered 18/12, 2012 at 16:18 Comment(1)
Hey...that looks more familiar ;).Brink
O
2

A fun one!

a = %w(do re mi fa)
a.length.times.zip a
Orlene answered 20/11, 2020 at 15:20 Comment(1)
In python, this would be zip(range(len(a)), a) just in case you're like me and had to run irb to catch on to this clever use of .times. Very niceBrink

© 2022 - 2024 — McMap. All rights reserved.