My Secret Life as a Spaghetti Coder
home | about | contact | privacy statement | getting started with cfrails
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!


Comments
Leave a comment

that's great thanks

Posted by Dibi Store on Dec 03, 2007 at 08:50 AM UTC - 5 hrs

Leave a comment

Leave this field empty
Your Name
Email (not displayed, more info?)
Website

Comment:

Subcribe to this comment thread
Remember my details
Google
Web CodeOdor.com

Me
Picture of me

Topics
.NET (21)
AI/Machine Learning (12)
C++ (4)
cfrails (22)
ColdFusion (80)
Customer Relations (15)
DRY (18)
DSLs (11)
Future Tech (4)
Games (5)
Groovy/Grails (7)
IDEs (8)
Java (41)
JavaScript (2)
Lisp (1)
Mac OS (1)
Miscellany (59)
OOAD (34)
Programming (97)
Programming Quotables (5)
Rails (18)
Ruby (50)
Save Your Job (40)
scriptaGulous (4)
Software Development Process (22)
TDD (39)
TDDing xorblog (6)
Tools (3)
Web Development (2)
YAGNI (10)

Resources
Agile Manifesto & Principles
Principles Of OOD
ColdFusion
CFUnit
Ruby
Ruby on Rails
JUnit

Reading List
InfoQ - Agile, Ruby, & more
Ray Camden - Cf Jedi Master
Ron Jeffries' XP Mag
Peter Bell's Application Generation
Others coming...

RSS 2.0: Full Post | Short Blurb
Subscribe by email:

Delivered by FeedBurner