yurisich
yurisich

Reputation: 7109

Python's enumerate in Ruby?

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"]] 

Upvotes: 28

Views: 11071

Answers (4)

Stev-0
Stev-0

Reputation: 31

A fun one!

a = %w(do re mi fa)
a.length.times.zip a

Upvotes: 2

Raindal
Raindal

Reputation: 3237

Maybe a quicker solution would be :

%w(a b c).map.with_index {|x, i| [i, x] }

Upvotes: 7

snurre
snurre

Reputation: 3105

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

Upvotes: 38

Ry-
Ry-

Reputation: 224857

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

Upvotes: 8

Related Questions