With a name like
, I thought you were going to iterate through all the
permutations of how I could construct a list
you operated upon. For example, I thought
[1,2,3,4].each_cons do |x| # I did not notice the required argument
So when I needed to find the local maxima in an image projection to
algorithmically find the staves in sheet music
found myself wanting a C-style
I didn't know you'd provide me with a wonderful sliding window!
[1,2,3,4].each_cons(2) do |x|
From now on, I'll turn to you when I need that functionality. Thanks for waiting
. Not everyone would be as patient as you.
PS: In case you're interested, the "cons" in "each_cons" is short for "consecutive," not "construct," as
Matz informed me:
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
Actually, isn't Enumerable#each_slice(2) a closer equivalent to the original each_pair implementation?
Posted by JayTee
on Nov 09, 2012 at 06:13 PM UTC - 5 hrs
Leave a comment
I'm guessing you mean this: http://www.codeodor.com/index.cfm/2007/12/3/Arraye...
when you're asking about "the original each_pair implemenation."
Is that right?
All three things do something different:
Let's use [1, 2, 3, 4] as an example.
#each_slice(2): will split the array on every 2nd element, so our example array would go through 2 iterations: one for [1,2] and the other for [3,4].
#each_pair will go through every combination of elements. The iterations using our example array would be:
Finally, #each_cons(2) will have a "sliding window" effect, yielding for each iteration:
Posted by Sammy Larbi
on Nov 10, 2012 at 12:17 PM UTC - 5 hrs