On Sep 19, 2008, at 9:34 PM, David Masover wrote:

> 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.

When I wrote the problem, I was thinking of this solution:

class Data2D; def [](x) lambda { |y| @data[y][x] } end

James Edward Gray II