Difference between each.with_index and each_with_index in Ruby?

I am really confused by the difference between each.with_index and each_with_index . They have different types, but in practice they seem the same.

+57
ruby
Nov 28 '13 at 5:02
source share
2 answers

The with_index method accepts an optional parameter to offset the starting index. each_with_index does the same, but does not have an 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 
+99
Nov 28 '13 at 5:09
source share
— -

each_with_index was previously introduced in Ruby. with_index was introduced later:

  • to ensure wider use with various meters.
  • so that the index starts with a number other than 0 .

Today, using with_index would be better in terms of generality and readability, but in terms of speeding up code, each_with_index works a little faster than each.with_index .

When you feel that one method can be easily expressed by a simple chain of several methods, it usually happens that a single method is faster than a chain. As for another example of this, reverse_each is faster than reverse.each . These methods have reason to exist.

+30
Nov 28 '13 at 5:47 on
source share



All Articles