From: Peter Zotov Date: 2011-02-20T19:56:14+09:00 Subject: Re: About the "def method=(param)",why compiled error? On Sun, 20 Feb 2011 19:51:22 +0900 Zengqh Mansion wrote: > very simple program: > > class Song > def initialize(duration) > @duration = duration > end > > def duration=(new_duration) > @duration = new_duration > end > end > > song = Song.new(260) > print song.duration > > > the compiler outputs: > D:/我的文档/Ruby/attr_writer.rb:12:in `
': undefined method > `duration' for > # (NoMethodError)。 > > appreciate for your help. > You have only defined a "duration=" method on your class, and an instance variable "@duration". Calling "song.duration" means invoking a method "duration" on object "song", which is not defined in class Song. You can define it this way: class Song def duration @duration end end Or, in more concise way, this way: class Song def initialize(duration) @duration = duration end attr_accessor :duration end Executing attr_accessor helper method in a class context is the same as the definition of two functions, "duration" and "duration=", as they're described above. You can also use attr_reader and attr_writer method; I hope their function is obvious. -- WBR, Peter Zotov