Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's enumerate in Ruby?

Tags:

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"]]  
like image 671
yurisich Avatar asked Dec 18 '12 16:12

yurisich


People also ask

What does enumerate () do in Python?

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.

Does Ruby have list?

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.

What is enumerate in pandas?

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.

Is enumerate or range faster?

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().


1 Answers

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 
like image 166
snurre Avatar answered Oct 06 '22 00:10

snurre