Ruby array hash keys

2019-07-15 13:00发布

Basically I'm working with a 2D matrix. I can access elements of the matrix by specifying an (x,y) pair to get the corresponding value at that position.

Now I also want to be able to keep track of certain pairs that are arbitrarily determined at run-time. For example, maybe I need to keep track of the values at (1,2), (3,4), and (5,6), and maybe I need to retrieve the value at that position frequently.

So I was thinking how about just make a hash .

liked_elements = {[1,2] => M[1,2], [3,4] =>M[3,4], [5,6]=>M[5,6]}

Or something like that.

Then I can quickly iterate over the hash and get the elements that I like.

Are there any issues with using arrays as hash keys?

标签: ruby
3条回答
来,给爷笑一个
2楼-- · 2019-07-15 13:19

If it's truly a matrix (an array of arrays), then you can just pass in coordinates like this

matrix = [[:a, :b, :c],[:d, :e, :f], [:g, :h, :i]]
matrix[0][1] # returns :b
matrix[1][2] # returns :f
matrix[2][3] # returns nil, since 3 is out of bounds

Yes, you can create an array as a hash key.

h = Hash[[0,1], matrix[0][1]]
h[[0,1]] # returns :b
查看更多
Lonely孤独者°
3楼-- · 2019-07-15 13:28

Just don't modify the array afterward (or remember to rehash the hash if you do).

查看更多
成全新的幸福
4楼-- · 2019-07-15 13:36

I am currently making a two-dimensional array where each array points to a specific hash-map. Each map hold their own specific data and I would like to retrieve key, and value information. However, when I reference an array (i.e. A[0][1] I cannot access the hash functions.

I checked the class type by using A.class to verify it was a Hash and indeed that is what it returns. Is this an inherent problem with Ruby 1.9.3 or am I doing something wrong?

查看更多
登录 后发表回答