From: Brian Candler Date: 2011-01-19T06:47:29+09:00 Subject: Re: Calling by Reference - Two Questions Mike Stephens wrote in post #975795: >>Robert Klemme wrote >> You cannot assign to self! >> Calling self#[]= is something different - this is actually a method >> that must be implemented for the object that self points to. > > Robert, can you expand on that? > > My example has an object of type Array. Array has a method = > implemented, so in what way is []= different to = ? One works on self; > the other raises an error. Array doesn't have an '=' method. When you write foo[bar] = baz this is just syntactic sugar for the following method call: foo.send(:[]=, bar, baz) i.e. the name of the method being called is '[]=' and we are passing it two arguments, bar and baz. So it's not an assignment. It's a method call; the implementation of this method may mutate the object (or may not). Try this test program: class Foo def []=(*args) puts "You sent #{args.inspect}" end end f = Foo.new f["hello"] = "world" Almost all things which look like operators in Ruby are actually method calls, and hence can be redefined. The exceptions are assignment (to local variables) and short-circuit boolean operators. Unary "!" can't be redefined in ruby 1.8, but I think it can in 1.9. -- Posted via http://www.ruby-forum.com/.