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

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 methodduration’
for
#<Song:0xb33f10 @duration=260> (NoMethodError)。

appreciate for your help.

On Sun, 20 Feb 2011 19:51:22 +0900
Zengqh M. [email protected] wrote:

end
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.

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 M. wrote in post #982758:

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.

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs