This code, from an example I found, counts the number of elements in the array which are equal to their index. But how ?
[4, 1, 2, 0].to_enum(:count).each_with_index{|elem, index| elem == index}
I could not have done it only with chaining, and the order of evaluation within the chain is confusing.
What I understand is we're using the overload of Enumerable#count
which, if a block is given, counts the number of elements yielding a true value. I see that each_with_index
has the logic for whether the item is equal to it's index.
What I don't understand is how each_with_index
becomes the block argument of count
, or why the each_with_index
works as though it was called directly on [4,1,2,0]
. If map_with_index
existed, I could have done:
[4,1,2,0].map_with_index{ |e,i| e==i ? e : nil}.compact
but help me understand this enumerable-based style please - it's elegant!
[4,1,2,0].map.with_index{ |e,i| e==i ? e : nil}.compact
– Franz[4,1,2,0].select.with_index{ |e,i| e==i}
– Franz