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

Crystal语言:如何重写to string方法实现对象可读输出?

重写Ruby对象的to_s方法实现可读输出

当你在控制台打印自定义User对象时,默认输出的#<User:0x7fdd9811eb80>只包含类名和内存地址,完全看不到对象的实际属性信息。要解决这个问题,只需要在自定义类中重写to_s方法,定义你想要的可读输出格式。

基础实现:硬编码属性

直接指定要展示的属性,输出格式更可控:

class User
  attr_accessor :name, :email, :age

  def initialize(name, email, age)
    @name = name
    @email = email
    @age = age
  end

  # 重写to_s方法,自定义输出内容
  def to_s
    "User(name: '#{@name}', email: '#{@email}', age: #{@age})"
  end
end

测试效果:

user = User.new("Alice", "alice@example.com", 30)
puts user  # 输出: User(name: 'Alice', email: 'alice@example.com', age: 30)

灵活实现:动态获取属性

如果类的属性经常变动,不想每次修改to_s,可以通过instance_variables动态遍历所有实例变量:

class User
  attr_accessor :name, :email, :age

  def initialize(name, email, age)
    @name = name
    @email = email
    @age = age
  end

  def to_s
    # 遍历所有实例变量,转换为"属性名: 值"的格式
    attributes = instance_variables.map do |var|
      attr_name = var.to_s.delete("@") # 去掉变量名前的@
      "#{attr_name}: #{instance_variable_get(var).inspect}"
    end.join(", ")
    "User(#{attributes})"
  end
end

这种方式下,哪怕后续给User类新增属性,to_s也能自动包含新属性的信息,无需手动修改方法。

内容的提问来源于stack exchange,提问作者R A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:50:19