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"]]
Python enumerate() Function The enumerate() function takes a collection (e.g. a tuple) and returns it as an enumerate object. The enumerate() function adds a counter as the key of the enumerate object.
In Ruby, since we don't have a “List” object, we can achieve the same thing using an array and the Array#unshift method like this: Internally, Ruby will create an array like this: Superficially, it appears that the unshift method on the Array class is equivalent to the cons function in Lisp.
The enumerate() function is a built-in function that returns an enumerate object. This lets you get the index of an element while iterating over a list. In other programming languages (C), you often use a for loop to get the index, where you use the length of the array and then get the index using that.
enumerate() is faster when you want to repeatedly access the list/iterable items at their index. When you just want a list of indices, it is faster to use len() and range().
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With