On Sep 19, 2008, at 6:43 PM, Matthew Moss wrote:

> First problem...
> You should know this pattern well:
>
>> [:one, "two", 4] * 3
>    => [:one, "two", 4, :one, "two", 4, :one, "two", 4]
>
> Write a single line method on Array that does this instead:
>
>> [:one, "two", 4].repeat(3)
>    => [:one, :one, :one, "two", "two", "two", 4, 4, 4]

class Array; def repeat(n) zip(*([self] * (n - 1))).flatten end end

> Post your solution AND a followup problem for others to solve.

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

James Edward Gray II