From: Philip Hallstrom Date: 2006-05-11T18:26:09+09:00 Subject: Re: Writable attributes - how does this work? > How does this actually work? > > from the Pick Axe book: > > irb> > 1> class Song > 2 > def duration=(new_duration) > 3> @duration = new_duration > 4> end > 5> end > 6> > 7> song = Song.new("Bicylops", "Fleck", 260) > 8> song.duration --> 260 > 9> song.duration = 257 > 10> song.duration --> 257 > > If a method name which is used to set the attribute is called > "duration=", how come that one can use song.duration = 257? > > I mean, does it just work lik this, because the Ruby engine recognizes > the 'set attribute' method just because of the = sign after the > "duration" on line number two? You'll probably get better answers from someone who is smarter than I am, but since it's late and I'm waiting for something to finish, here's how I think about it... Stop thinking of =, ==, +, *, <=,.... as operators. Think of them as methods. So, when you see "a = b" that's really saying call the method "=" on the object "a" passing as an argument "b". If you think of it that way then when you see the below method it will make more sense. def a= (b) @a = b end So, "a + b" is really: def a+ (b) return a + b end (yes, I know the return is unecessary, just trying to be clear :) Hope that helps.