It's not a hard thing to come up with, but it's incredibly useful. Suppose you need to
iterate over each pair of values or indices in an array. Do you really want to
duplicate those nested loops in several places in your code? Of course not. Yet
another example of why code as data is such a powerful concept:
class Array
# define an iterator over each pair of indexes in an array
def each_pair_index
(0..(self.length-1)).each do |i|
((i+1)..(self.length-1 )).each do |j|
yield i, j
end
end
end
# define an iterator over each pair of values in an array for easy reuse
def each_pair
self.each_pair_index do |i, j|
yield self[i], self[j]
end
end
end
Now you can just call
array.each_pair { |a,b| do_something_with(a, b) }
.
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
that's great thanks
Posted by Dibi Store
on Dec 03, 2007 at 08:50 AM UTC - 5 hrs
Just use Enumerable#each_cons(2)
Posted by johno
on Sep 07, 2010 at 04:21 AM UTC - 5 hrs
Good call johno.
Posted by
Sammy Larbi
on Sep 07, 2010 at 07:46 AM UTC - 5 hrs
I know I'm coming to this party late... but Enumerable#each_cons(2) only gives consecutive pairs, whereas Sam's code yields all pairs.
e.g. [1,2,3].each_cons(2) # => [[1,2], [2,3]]
Sam's code gives [[1,2],[1,3],[2,3]].
However, the same thing can be done with Array#combination(2)
Posted by charliebah
on Dec 12, 2011 at 01:47 PM UTC - 5 hrs
Haha, you know it's funny that four years after this post I was writing about each_cons and how with it's name, I thought it would have been combination.
The 4 years later version is here:
http://codeodor.com/index.cfm/2011/10/24/Im-sorry-... if you're interested.
Thanks for reminding me about this charlie.
Posted by
Sammy Larbi
on Dec 12, 2011 at 02:47 PM UTC - 5 hrs
Leave a comment