You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby代码运行报undefined method `duration'的NoMethodError如何解决

问题排查与解决方案

错误原因

Ruby的类实例变量默认是私有属性,不允许外部直接访问。你虽然在initialize方法中给@duration完成了赋值,但没有定义对应的对外访问方法,所以外部调用.duration属性时就会抛出undefined method错误。

修复方案

在Song类中添加duration属性的读取方法即可,推荐使用Ruby内置的attr_reader语法快速生成Getter方法,修改后的完整可运行代码如下:

class Song
    # 新增此行,自动生成name、artist、duration三个属性的只读方法
    attr_reader :name, :artist, :duration
    @@play = 0;  #类变量必须在使用前定义
    
    def initialize(name, artist, duration)
        @name = name
        @artist = artist
        @duration = duration
        @plays = 0
    end

    def play
        @plays += 1 #等价于 @plays = @plays + 1
        @@play += 1
        "This song: #@plays plays. Total #@@play plays"
    end

end

class SongList
    Max_Time = 5*60

    def self.is_too_long(song)
        return song.duration > Max_Time
    end
end

song1 = Song.new("Bicyclops", "Fleck", 260)
p song1.duration # 输出 260

p SongList.is_too_long(song1) # 输出 false,260秒小于300秒(5分钟)

如果你不想用语法糖,也可以手动定义读取方法,效果完全一致:

def duration
  @duration
end

内容的提问来源于stack exchange,提问作者Dwayne Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 16:54:01