I like this functional style:
module Enumerable def diff each_cons(2).map {|pair| pair.reverse.reduce :-} end end
EDIT: I just realized that reverse completely unnecessary. If it were a functional language, I would use pattern matching, but Ruby does not support pattern matching. However, it does support destructive binding, which is a good enough approximation for pattern matching in this case.
each_cons(2).map {|first, second| second - first}
No emoticons.
I like how it sounds if you just read it loudly from left to right: "For each pair, apply the difference between the first and second elements of the pair." Actually, I usually don't like the name collect and prefer map instead, but in this case it looks even better:
each_cons(2).collect {|first, second| second - first}
"For each pair, collect the difference between its elements." It almost sounds like a first-order difference.
Jörg W Mittag
source share