code bites
I’ve written a metric ton of code over the past week and a bit (code can be measured by the weight of all the rainforests you would destroy should you be forced to print it out).
Some of it was Ruby (without Rails), and a little Javascript. Both of those guys allow you to redefine core classes (like “Array”), so without further ado, here are a couple of useful additions to the core “Array” classes.
ObjectextendArrayprototype
if !connector connector = "and";
switchthislength
case 0: result = ""; break;
case 1:
result = this0toString; break;
case 2:
result = this0toString + " " + connector + " " + this1toString; break;
default:
result = thisslice0thislength - 1join", " + " " + connector + " " + thisthislength - 1toString;
return result;
;
This is an (almost) exact port of ActiveSupport’s to_sentence. I wonder why it’s not in Prototype? Perhaps I should submit a patch :) I’ve also got a really basic Inflector port, if anyone’s interested.
# find the value in an array with the largest number of occurences
inject(slice(0)) do |most_popular, contender|
(occurences(most_popular) > occurences(contender)) ? most_popular : contender
end
end
# we'll cache the occurences of a particular value,
# because most_popular value will call it lots
@occurences ||= {}
@occurences[value] || find_all {|v| v == value }.size
end
end
Those are a couple methods on Ruby’s Array that were useful for writing my K-Nearest Neighbour algorithm (a university project).
P.S - spot the pun in the title.




Nik Wakelin
Oliver Clarke
It would appear my code lines are too long :(