With a name like
each_cons
, 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
puts x.inspect
end
would output:
[[1,2,3,4], []]
[[1,2,3], [4]]
[[1,2], [3,4]]
[[1], [2,3,4]]
[[], [1,2,3,4]]
So when I needed to find the local maxima in an image projection to
algorithmically find the staves in sheet music, I
found myself wanting a C-style
for
loop.
I didn't know you'd provide me with a wonderful sliding window!
[1,2,3,4].each_cons(2) do |x|
puts x.inspect
end
[1, 2]
[2, 3]
[3, 4]
From now on, I'll turn to you when I need that functionality. Thanks for waiting
on me,
each_cons
. Not everyone would be as patient as you.
Warm Regards,
Sam
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 - 6 hrs
Hey JayTee,
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:
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
Finally, #each_cons(2) will have a "sliding window" effect, yielding for each iteration:
[1, 2]
[2, 3]
[3, 4]
Posted by
Sammy Larbi
on Nov 10, 2012 at 12:17 PM UTC - 6 hrs
Leave a comment