Donnerstag, April 20, 2006

Object-oriented "chop"

Dave (you know, one of the pragmatic programmers) provides mini exercices, so-called Katas, on his blog. I have discovered them recently although he put the Katas up there in 2003. Following you find my fifth implementation of the chop-algorithm of Kata 2:

class Array
def middle
size / 2
end

def partition(target)
in_lower?(target) ? self[0 ... middle] : self [middle .. -1]
end

def in_lower?(target)
self[middle] > target
end

def offset(target)
in_lower?(target) ? 0 : middle
end

def chop(target, offset = 0)
if (size <= 1)
self[0] == target ? offset : -1
else
partition(target).chop(target, offset(target) + offset)
end
end
end

def chop(target, items)
items.chop(target)
end


Did I already mention I really like Ruby's open classes? :) My implementation was initially inspired by Jim Weirich's recursive implementation.