On Tue, Nov 19, 2013 at 10:59 PM, aaron v. <lists / ruby-forum.com> wrote:
> Class SparseVector
>     attr_reader :vector
>
>     def initialize(h = {})
>         @vector = Hash.new(0)
>         @vector = @vector.merge!(h)
>     end
>
>     def [](i)
>         @vector[i]
>     end
>
>     def to_s
>         @vector.to_s
>     end
> end
>
> class SparseMatrix
>
>     attr_reader :matrix
>
>     def initialize(h = {})
>         @matrix = Hash.new({})
>         for k in h.keys do
>             @matrix[k] = if h[k].is_a? SparseVector
>             h[k]
>         else
>             @matrix[k] = SparseVector.new(h[k])
>         end
>     end
> end
>
>     def [](i)
>         @matrix[i]
>     end
>
>     def col(j)
>         c = {}
>         for r in @matrix.keys do
>             c[r] = @matrix[r].vector[j] if
> @matrix[r].vector.keys.include? j
>         end
>         SparseVector.new c
>     end
> end
>
> hsh = SparseMatrix.new 1 => {1 => 33, 2 => 44, 3 => 55}, 2 => {1 => 66,
> 3 => 77}
> puts hsh[1][3]
> puts hsh.col(2)
>
> That's the code I have, I need to know if I can if I can get the indexes
> of the hash looping through the hash.
> I've tried using each-do, but i couldn't make it work.

Since you are nesting Hashes you need a recursive approach at finding
all indexes.

def each_index
  return enum_for(each_index) unless block_given?

  each_entry(@matrix, []) {|i,| yield i}
  self
end

def each_entry(hash, index_prefix, &b)
  hash.each do |key, value|
    idx = index_prefix + [key]

    if Hash === value
      each_entry(value, idx, &b)
    else
      yield idx, value
    fi
  end
end

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/