新手问题 很粗浅的问题,按书的代码输提示错误。

ying39 · 2013年12月21日 · 最后由 lgn21st 回复于 2013年12月22日 · 2054 次阅读

今天正式开始看 Programming Ruby 中文版,第 66 页按书中代码输入,结果运行提示错误,不知道何原因,很初级了,想不明白。

air-mxtekiMacBook-721:PR 721-mx$ ruby pr63.rb
pr63.rb:2:in `initialize': wrong number of arguments (4 for 3) (ArgumentError)
    from pr63.rb:21:in `new'
    from pr63.rb:21:in `<main>'



class Song
    def initialize(name,artist,duration)
        @name =name
        @artist =artist
        @duration = duration
    end

    def to_s
        "Song: #@name  #@artist(#duration)"
    end

end

class KaraokSong < Song
    def initailize(name,artist,duration,lyrics)
    super(name,artist,duration)
    @lyrics=lyrics
    end
end

song = KaraokSong.new("adsf","dsaf",34234,"234")
song.to_s
1 楼 已删除

class 的初始化方法是 initialize , 好好检查一下你的拼写。

错误信息提示的很清楚,小伙伴

#2 楼 @lgn21st @xiaogui 非常感谢,太粗心了,检查好几遍居然没发现问题是拼写。不过下一步又遇到问题,这次检查了下没发现问题出在哪里。

提示错误:PR63.rb:21:in `to_s': undefined method `+' for nil:NilClass (NoMethodError)
    from PR63.rb:26:in `<main>'

class KaraokSong < Song
    def initialize(name,artist,duration,lyrics)
    super(name,artist,duration)
    @lyrics=lyrics
    end

    def to_s
        super+ "[#@lyrics]"
    end
end

song = KaraokSong.new("adsf","dsaf",34234,"234")
song.to_s

#4 楼 @ying39 没有遇到任何问题:

~ $ irb
>> class Song
>>       def initialize(name,artist,duration)
>>             @name =name
>>             @artist =artist
>>             @duration = duration
>>         end
>>
?>         def to_s
>>             "Song: #@name  #@artist(#duration)"
>>         end
>>
?>     end
=> nil
>> class KaraokSong < Song
>>       def initialize(name,artist,duration,lyrics)
>>         super(name,artist,duration)
>>         @lyrics=lyrics
>>         end
>>
?>         def to_s
>>             super+ "[#@lyrics]"
>>         end
>>   end
=> nil
>> song = KaraokSong.new("adsf","dsaf",34234,"234")
=> #<KaraokSong:0x007fc91185b290 @name="adsf", @artist="dsaf", @duration=34234, @lyrics="234">
>> song.to_s
=> "Song: adsf  dsaf(#duration)[234]"
需要 登录 后方可回复, 如果你还没有账号请 注册新账号