On Friday 19 September 2008 21:11:21 Patrick Doyle wrote:
> > Given the class:
> >
> >  class Data2D
> >    def initialize
> >      @data = [ ]  # in row major form
> >    end
> >
> >    def add_row(*row)
> >      @data << row
> >    end
> >  end
> >
> > And this setup for an object:
> >
> >  data = Data2D.new
> >  data.add_row(1, 2, 3, 4)
> >  data.add_row(5, 6, 7, 8)
> >
> > Define a [] method for the class that makes this form of access possible:
> >
> >  x = 2
> >  y = 1
> >  data[x][y]  # => 7
> >
> How about
> 
> def [](i)
>   @data.map {|row| row[i]}
> end

Curses! You beat me to it, so I wrote a more complex solution:

class Data2D
  def [](x)
    d=@data; Class.new{ define_method('[]') {|y| d[y][x]}}.new
  end
end

Counting spaces, it's 64 characters, so it still fits. It has the advantage of 
probably being faster on very large datasets, at least for that single 
lookup, as no array splicing is done.

I didn't really have a problem in mind, but here's an easy one: Write an []= 
method to solve the following:

obj = YourClass.new
obj['answer'] = 42
obj.answer  # => 42