关于ruby中类方法调用实例变量出错
class Song
@@plays = 0
def initialize(name,artist,duration)
@name = name
@artist = artist
@duration = duration
end
def play
@plays += 1
@@plays += 1
puts "This song:#@plays plays.Total #@@plays plays."
end
end
class SongList
MaxTime = 5 * 60
def SongList.isTooLong(aSong)
c = aSong.duration > MaxTime
return c
end
end
s1 = Song.new("qwe","asdf",123)
puts SongList.isTooLong(s1)
s2 = Song.new("qwreqw","zxczx",234)
puts SongList.isTooLong(s2)
错误:
test.rb:18:in `isTooLong': undefined method `duration' for #<Song:0xaf6ab8 @name="qwe", @artist="asdf", @duration=123> (NoMethodError)
from test.rb:24:in `<main>'
[解决办法]
实例变量是不允许外部访问的,需要自己写 def name ;end, def name= ; end方法,或使用attr_accessor方法生成
[code=Ruby]
class Song
attr_accessor :name, :artist, :duration
@@plays = 0
def initialize(name,artist,duration)
@name = name
@artist = artist
@duration = duration
end
def play
@plays += 1
@@plays += 1
puts "This song:#@plays plays.Total #@@plays plays."
end
end
class SongList
MaxTime = 5 * 60
def SongList.isTooLong(aSong)
c = aSong.duration > MaxTime
return c
end
end
s1 = Song.new("qwe","asdf",123)
puts SongList.isTooLong(s1)
s2 = Song.new("qwreqw","zxczx",234)
puts SongList.isTooLong(s2)
[/code]