Andrew Andrew - 2 months ago 15
Ruby Question

Ruby - Using syntactic sugar bracket method to return a value in 2-D array

A basic example of what is confusing me:

def [](row, col)
self[row][col]
end

x = [[1,3], [4,5]]
x[0][0] #normal
x[0, 0] #syntactic sugar?


I have been told that these are equivalent statements, but when I run the sugar one, I get a different answer. How am I supposed to write it in syntactic sugar?

Answer

You need to put your def [](row, col) method in a class that contains your data. So something like:

$ irb
2.3.0 :001 > class MyData
2.3.0 :002?>   attr_accessor :my_array
2.3.0 :003?>   def [](row, col)
2.3.0 :004?>     my_array[row][col]
2.3.0 :005?>     end
2.3.0 :006?>   end
 => :[]
2.3.0 :007 > x = MyData.new
 => #<MyData:0x007f96dc8024b8>
2.3.0 :008 > x.my_array = [[1, 3], [4, 5]]
 => [[1, 3], [4, 5]]
2.3.0 :009 > x[1,1]
 => 5
2.3.0 :010 >