From: "Jesús Gabriel y Galán" Date: 2008-12-03T18:01:28+09:00 Subject: Re: Question about op. overloading On Wed, Dec 3, 2008 at 9:49 AM, Maarten Mortier wrote: > I have: > > class Sudoku > def[](r,c) > @rows[r][c] > end > > def set(r,c,a) > @rows[r][c]=a > end > end > > Now, how can I define a []= operator instead of the awkward set(r,c,a) ? > I want to be able to do > sudoku[2,3]=candidate > > or even > sudoku[2][3] = candidate > and > sudoku[3] = row > > Are these things possible? How, I could not find the information. A []= operator is possible. It's syntactic sugar for a method named "[]=" and at least two parameters: what's inside the brackets and the "assigned" value. An example: irb(main):001:0> class A irb(main):002:1> def []= (a,b) irb(main):003:2> @x[a] = b irb(main):004:2> end irb(main):005:1> attr_reader :x irb(main):006:1> def initialize irb(main):007:2> @x = {} irb(main):008:2> end irb(main):009:1> end => nil irb(main):010:0> a = A.new => # irb(main):011:0> a[:a] = :b => :b irb(main):012:0> a => #:b}> If you add more parameters to the method, you can use more "keys" inside the brackets: irb(main):013:0> class A irb(main):014:1> def []= (a,b,c) irb(main):015:2> puts a,b,c irb(main):016:2> end irb(main):017:1> end => nil irb(main):018:0> a = A.new => # irb(main):019:0> a[:a,:b] = :c a b c => :c Hope this helps, Jesus.