von spotz
von spotz

Reputation: 905

Ruby multi-dimensional getter/setter methods (C++-like)

is there a way to have 'C'/'C++'-like multi-dimensional variables, that is, define multi-dimensional bracketed getter/setter-methods? (without resorting to Hash)

Can't one define

def [][]=(a, b, value)
  ...
end

Such that

a = Integer.new
a[1][1] = 2

?

A Hash should not compensate a proper table. And I think I could remember how once it was shown on stackoverflow how to define multidimensional brackets as method. Yet I can't find the thread, if it existed.

Upvotes: 0

Views: 46

Answers (1)

claasz
claasz

Reputation: 2144

Since C++ and Ruby are so fundamentally different, I'm not sure the question

is there a way to have 'C'/'C++'-like multi-dimensional variables in Ruby?

does even make sense.

Instead of trying a hard to mimick a C++ feature in Ruby, you should ask yourself what is the real problem you want to solve and how can you achieve it using common Ruby features.

When you see the [][] "operator" in Ruby, it is most of the time actually the [] operator returning an Array or a Hash (as pointed out by mu-is-too-short already).

E.g.

$ irb
2.6.2 :001 > a = Array.new(3, "0")
 => ["0", "0", "0"] 
2.6.2 :002 > b = Array.new(3, a)
 => [["0", "0", "0"], ["0", "0", "0"], ["0", "0", "0"]] 
2.6.2 :003 > b[1][1]
 => "0" 

Upvotes: 1

Related Questions