Ruby: access to array element hint
I have a big 2-dimensional array A
, and also a flat array B
of two elements. How can I quickly access element from the A
array using numbers (coordinates) in B
? The only thing I can do now is:
A[B[0],B[1]]
But the path to these actual arrays through the names of members of my class is too long and dirty, and the act开发者_开发百科ual array names are too long... so I wonder if its possible to ease the job.
x = B[0]
y = B[1]
A[x][y]
What about turning A into a Hash with two-element arrays as keys? So where you now have something like this:
A = [["TopL","TopR"],["CenterL","CenterR"],["BottomL","BottomR"]]
B = [[0,1],[1,0],[2,1]]
A[B[x][0]][B[x][1]]
You'd instead have:
A = {[0,0] => "TopL", [0,1] => "TopR", [1,0] => "CenterL", [1,1] => "CenterR", [2,0] => "BottomL", [2,1] => "BottomR"}
B = [[0,1],[1,0],[2,1]]
A[B[x]]
Dunno if that'll help in your actual situation, but maybe it'll give you some ideas.
精彩评论