Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between each.with_index and each_with_index in Ruby?

Tags:

ruby

I'm really confused about the difference between each.with_index and each_with_index. They have different types but seem to be identical in practice.

like image 266
Stan Avatar asked Nov 28 '13 05:11

Stan


People also ask

What is Each_with_index in Ruby?

The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object. Syntax: A.each_with_index. Here, A is the initialised object. Parameters: This function does not accept any parameters. Returns: the value of the given object.

How do you add to an array in Ruby?

push() is a Ruby array method that is used to add elements at the end of an array. This method returns the array itself.

How do you slice an array in Ruby?

slice() in Ruby? The array. slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.

What is the difference between each_with_index and with_index in Ruby?

The with_index method takes an optional parameter to offset the starting index. each_with_index does the same thing, but has no optional starting index. Show activity on this post. each_with_index was introduced into Ruby earlier. with_index was introduced later: to allow wider usage with various enumerators.

How to get the current index of an element while iterating?

To get around this, Ruby has a method called each_with_index that allows us to access the current element index while iterating. each_with_index is more elegant than using an extra variable to keep track of the current index. It exposes the index of iteration as the second argument of a block.

What are the disadvantages of using index variables?

The first issue is that it added two additional lines of code, and more code means more potential bugs. The second issue is that the index variable becomes orphaned after execution. If another chunk of code below uses the same variable name, this could become a problem. Confused Between DEM, DTM and DSM !


1 Answers

The with_index method takes an optional parameter to offset the starting index. each_with_index does the same thing, but has no optional starting index.

For example:

[:foo, :bar, :baz].each.with_index(2) do |value, index|     puts "#{index}: #{value}" end  [:foo, :bar, :baz].each_with_index do |value, index|     puts "#{index}: #{value}" end 

Outputs:

2: foo 3: bar 4: baz  0: foo 1: bar 2: baz 
like image 157
blacktide Avatar answered Sep 28 '22 10:09

blacktide