MST
星途 面试题库

面试题:Ruby中实现复合赋值运算符重载

定义一个 `MyString` 类,它有一个实例变量 `@text` 用于存储字符串。要求在 `MyString` 类中重载复合赋值运算符 `<<`,使其能将一个字符串追加到 `@text` 上,同时还能实现链式调用,如 `a << 'b' << 'c'`,并返回最终的 `MyString` 对象。
40.7万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
class MyString
  attr_accessor :text

  def initialize(text = '')
    @text = text
  end

  def <<(other)
    @text << other.to_s
    self
  end
end