About the "def method=(param)",why compiled error?

Discussion in 'Ruby' started by Zengqh Mansion, Feb 20, 2011.

  1. very simple program:

    class Song
    def initialize(duration)
    @duration =3D duration

    def duration=3D(new_duration)
    @duration =3D new_duration

    song =3D Song.new(260)
    print song.duration

    the compiler outputs=EF=BC=9A
    D:/=E6=88=91=E7=9A=84=E6=96=87=E6=A1=A3/Ruby/attr_writer.rb:12:in `<main>=
    ': undefined method `duration'
    #<Song:0xb33f10 @duration=3D260> (NoMethodError)=E3=80=82

    appreciate for your help.

    -- =

    Posted via http://www.ruby-forum.com/.=
    Zengqh Mansion, Feb 20, 2011
    1. Advertisements

  2. Zengqh Mansion

    Peter Zotov Guest

    You have only defined a "duration=3D" 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

    Or, in more concise way, this way:

    class Song
    def initialize(duration)
    @duration =3D duration
    attr_accessor :duration

    Executing attr_accessor helper method in a class context is the same as
    the definition of two functions, "duration" and "duration=3D", as they're
    described above. You can also use attr_reader and attr_writer method; I
    hope their function is obvious.

    WBR, Peter Zotov
    Peter Zotov, Feb 20, 2011
    1. Advertisements

  3. thanks very much.
    i was reading the book "programming ruby".
    it said "def attribute=(new_attribute)", can be used attribute as if
    it's public variables, i think i was wrong.
    Zengqh Mansion, Feb 20, 2011
  4. Zengqh Mansion

    Jiawei Yong Guest

    Zengqh Mansion wrote in post #982758:
    Do not have the book, but I'm guessing that statement was made in a
    particular context.

    def attribute=(new_attribute) does allow you to use attribute as a
    public variable, when you are setting new value for attribute.

    If you have subsequently proceeded to code def attribute as Peter has
    suggested above, that will allow you to use your attribute as a public
    variable when it comes to getting value of attribute.

    Nevertheless, attr_accessor, attr_reader and attr_writer should be
    betterfor getter and setter.
    Jiawei Yong, Feb 21, 2011
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.