Forum: Ruby Hashed matrix

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
76cb21509ce97cfbe2643a675291b9cc?d=identicon&s=25 Yoann Moreau (yoniblond)
on 2009-04-20 12:04
Hello, I'd like to use a specific matrix with string as key for lines
and integer index for columns. I could also use string for columns (a
string version of integer), it doesn't matter. I use the matrix to store
a small object (named State) I just need to access data like that :
matrix[a_string][a_number]

Here is how I tried to do it :
matrix = Hash.new{ |hash, key| hash[key] = Array.new(5, State.new(0,
"")) }

But I have strange values, is there a better way to make that matrix ?
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-04-20 13:02
(Received via mailing list)
2009/4/20 Yoann Moreau <yoni612@hotmail.com>:
> Hello, I'd like to use a specific matrix with string as key for lines
> and integer index for columns. I could also use string for columns (a
> string version of integer), it doesn't matter. I use the matrix to store
> a small object (named State) I just need to access data like that :
> matrix[a_string][a_number]
>
> Here is how I tried to do it :
> matrix = Hash.new{ |hash, key| hash[key] = Array.new(5, State.new(0,
> "")) }

You want the block form of Array.new because otherwise all array
entries point to the same object:

matrix = Hash.new{ |hash, key| hash[key] = Array.new(5) {
State.new(0,"") } }

Alternative approach: use an Array of String and Fixnum as Hash key:

class Matrix
  def initialize
    @hash = Hash.new {|h,k| h[k] = State.new(0, "")}
  end

  def [](row,col)
    @hash[[row, col]]
  end

  def []=(row,col, val)
    raise ArgumentError, "Not a state %p" % val
    @hash[[row, col]] = val
  end
end

This is likely more efficient if your matrices are large and sparse.

Kind regards

robert
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-04-20 13:03
(Received via mailing list)
2009/4/20 Robert Klemme <shortcutter@googlemail.com>:
>
>  end
>
>  def [](row,col)
>    @hash[[row, col]]
>  end
>
>  def []=(row,col, val)
>    raise ArgumentError, "Not a state %p" % val

This should have read

raise ArgumentError, "Not a state %p" % val unless State === val
76cb21509ce97cfbe2643a675291b9cc?d=identicon&s=25 Yoann Moreau (yoniblond)
on 2009-04-20 13:15
Thanks for your answer, you're right I had the same object in my array,
this is why I had strange values.
I use a really small matrix so it's not a big deal to be efficient, I'll
use your first idea.

Thank you.
This topic is locked and can not be replied to.