On Sun, 20 Feb 2011 19:51:22 +0900
Zengqh Mansion <zengqh.mansion / gmail.com> 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 `<main>': undefined method
> `duration' for
> #<Song:0xb33f10 @duration=260> (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
  <skip>
  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