4

In Ruby 1.8.7 and prior, Enumerable::each_with_index did not accept any arguments. In Ruby 1.9, it will accept an arbitrary number of arguments. Documentation/code shows that it simply passes those arguments along to ::each. With the built in and standard library Enumerables, I believe passing an argument will yield an error, since the Enumerable's ::each method isn't expecting parameters.

So I would guess this is only useful in creating your own Enumerable in which you do create an ::each method that accepts arguments. What is an example where this would be useful?

Are there any other non-obvious consequences of this change?

Ryan
  • 2,073
  • 1
  • 19
  • 33

1 Answers1

2

I went through some gems code and found almost no uses of that feature. One that it does, spreadsheet:

def each skip=dimensions[0], &block
  skip.upto(dimensions[1] - 1) do |idx|
    block.call row(idx)
  end
end

I don't really see that as an important change: #each is the base method for classes that mix-in module Enumerable, and methods added (map, select, ...) do not accept arguments.

tokland
  • 66,169
  • 13
  • 144
  • 170
  • `each_with_object` accepts arguments. Hope I'm not being too argumentative! – Andrew Grimm Oct 30 '11 at 22:36
  • 1
    @Andrew, but each_with_object is an inject in disguise, so it's only natural you need an argument. I must admit, though, that I am not really sure about all this each thing, whether allowing arguments to each is important (or will be important) or just a minor detail. For my taste, in any case, each -being the base iterator- should accept no arguments. – tokland Oct 30 '11 at 22:43
  • One difference between `reduce` and `each_with_object` is that only the latter returns an enumerator when no block is given. Isn't that a significant difference? – Cary Swoveland Feb 14 '15 at 02:40