Search code examples
rubyeachsparse-array

Creating each method for custom two dimensional array


I followed these instructions to create a custom class for two dimensional arrays.

class SparseArray
  attr_reader :hash

  def initialize
    @hash = {}
  end

  def [](key)
    hash[key] ||= {}
  end

  def rows
    hash.length   
  end

  alias_method :length, :rows
end

How can I modify this class so I can iterate through the first and second level of an object using Object#each do? Please explain in simple terms, I'm a newbie.

Example of how I would use the each method on an object:

sparse_array[0][0] = "row 1 column 1"
sparse_array[0][1] = "row 1 column 2"
sparse_array[1][0] = "row 2 column 1"

sparse_array.each do |row|
  # sparse_array[0] on first iteration
  row.each do |column|
    # sparse_array[0][0] on first iteration
  end
end

Solution

  • You should define each method on your SparseArray and use it to wrap values of the wrapped hash:

    def each &block
      @hash.values.each(&block)
    end