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

Ruby中如何在一个类内调用另一个类实例对象的方法?

问题原因

你给出的代码存在两处会导致执行中断/逻辑不符合预期的问题:

  • Inner类的id方法存在语法错误,字符串拼接操作漏了+运算符,同时如果传入的id、number是数值类型,直接拼接字符串会抛出类型错误,需要统一转成字符串处理
  • Outer类的id方法中,return后的拼接逻辑拆分为两行写时,第一行末尾直接换行,Ruby解析时会认为return语句在第一行就已经执行完毕,直接返回"Outer id:\n",后面的拼接代码完全不会运行,这是输出中断的核心原因

修复方案

优先推荐使用Ruby原生的字符串插值语法替代手动+拼接,写法更简洁也能避免大量运算符漏写、换行解析错误这类问题,修复后代码如下:

class Inner
    attr_accessor :id, :number
    def initialize(id, number)
      @id                    = id
      @number                = number
    end
    def id()
      # 用字符串插值实现拼接,自动处理类型转换
      return "#{@id}_#{@number}"
    end
end

class Outer
    attr_accessor :id, :inner, :another
    def initialize(id, inner, another)
      @id                    = id
      @inner                 = inner # Inner类对象的实例变量
      @another               = another
    end
    def id()
      # 整个拼接逻辑用字符串插值实现,无需手动处理换行和运算符
      return "Outer id:\n#{@id}\nInner : #{@inner.id()}\nAnother: #{@another}\n"
    end
end

如果你坚持要用+拼接的写法,只需要把换行的+移到上一行末尾,告诉Ruby当前语句还未结束即可:

def id()
  return "Outer id:\n" +
  @id.to_s + "\nInner : " + @inner.id() +"\nAnother: " + @another.to_s + "\n"
end

内容的提问来源于stack exchange,提问作者Talk about nostalgia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:51:03