0

Is it preferable not to concatenate each and with with_index like this

array.each_with_index { ... }

or is concatenation perfectly acceptable?

array.each.with_index  { ... }
the_prole
  • 8,275
  • 16
  • 78
  • 163
  • 1
    http://stackoverflow.com/questions/20258086/difference-between-each-with-index-and-each-with-index-in-ruby – Deepak Mahakale Feb 24 '17 at 02:48
  • 2
    Note that [Enumerator#with_index](http://ruby-doc.org/core-2.3.0/Enumerator.html#method-i-with_index) (unlike [Enumerable#each_with_index](http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_index)) takes an optional argument that equals the first index (defaulting to zero) . So if you wish the indexing to begin at `1`, say, you could write `.each.with_index(1)` rather than `.each_with_index`. If `i` is the block variable, this may avoid the need to write `i+1` within the block. – Cary Swoveland Feb 24 '17 at 05:17

1 Answers1

3

Both of these forms is correct and will work. In the case listed however, the first form is preferred as it uses the purpose built method for this task.

The second form should normally be reserved for methods that do not have a with index option as in this silly bit of code:

['a', 'b', 'c', 'd'].select.with_index {|_d, i| (i%2)==0} 

which has as output:

["a", "c"]
Peter Camilleri
  • 1,882
  • 15
  • 17