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.

Object.extend(Array.prototype, {

  to_sentence : function(connector) {

    if (!connector) connector = "and";

    switch(this.length) {

      case 0:  result = ""; break;

      case 1:
        result = this[0].toString(); break;

      case 2:
        result = this[0].toString() + " " + connector + " " + this[1].toString(); break;

      default:
        result = this.slice(0, this.length - 1).join(", ") + " " + connector + " " + this[this.length - 1].toString();

    }

    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.

class Array

  # find the value in an array with the largest number of occurences
  def most_popular_value
    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
  def occurences(value)
    @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.


what other people thought

It would appear my code lines are too long :(

Nik, May 13th, 2008 at 7:17 pm

I like your code highlighting - sesky.

James, May 19th, 2008 at 3:01 pm

have your say