如何打印一个对象

huangapple go评论66阅读模式
英文:

How to print an object

问题

如何在引用对象时更改puts打印的内容?

考虑以下代码:

class MyClass
    attr_accessor :var
    def initialize(var)
        @var = var
    end
    # ...
end
obj = MyClass.new("content")
puts obj # 打印 #<MyClass:0x0000011fce07b4a0>,但我希望它打印 "content"
英文:

How do you change what is printed with puts when an object is referenced?

Consiser the following code:

class MyClass
    attr_accessor :var
    def initialize(var)
        @var = var
    end
    # ...
end
obj = MyClass.new(&quot;content&quot;)
puts obj # Prints #&lt;MyClass:0x0000011fce07b4a0&gt; but I want it to print &quot;content&quot;

I imagine that there is an operator that you can overload (or something similar), but I don't know what it's called so I have no clue what to search for to find the answer.

答案1

得分: 1

class MyClass
  attr_accessor :var
  def initialize(var)
    @var = var
  end

  def to_s
    @var
  end
end

obj = MyClass.new("content")
puts obj # 打印 "content"
英文:
class MyClass
  attr_accessor :var
  def initialize(var)
    @var = var
  end

  def to_s
    @var
  end
end

obj = MyClass.new(&quot;content&quot;)
puts obj # Prints &quot;content&quot;

答案2

得分: 1

摘自puts文档:

puts(*objects)nil

将给定的对象写入流中,该流必须处于可写状态;返回nil。对于不以换行序列结尾的每个对象,在其后写入一个换行符。[...]

对每个对象的处理:

  • 字符串:写入字符串。
  • 既不是字符串也不是数组:写入object.to_s
  • 数组:写入数组的每个元素;数组可以嵌套。

这意味着:您传递给puts的对象不是字符串,因此,在将字符串输出到IO之前,Ruby会调用该对象的to_s方法。因为您的对象没有实现to_s方法,所以将使用从Object#to_s继承的默认实现。

要返回自定义输出,只需像这样添加自己的to_s方法到您的类中:

class MyClass
  attr_accessor :var

  def initialize(var)
    @var = var
  end

  def to_s
    var
  end
end
英文:

Quote from the documentation of puts:

> puts(*objects)nil
>
> Writes the given objects to the stream, which must be open for writing; returns nil. Writes a newline after each that does not already end with a newline sequence. [...]
>
> Treatment for each object:
>
> - String: writes the string.
> - Neither string nor array: writes object.to_s.
> - Array: writes each element of the array; arrays may be nested.

That means: The object you pass to puts is not a string, therefore, Ruby will call to_s on that object before outputting the string to IO. Because your object has no to_s method implemented, the default implementation from Object#to_s.

To return a customize output, just add your own to_s method to your class like this:

class MyClass
  attr_accessor :var

  def initialize(var)
    @var = var
  end

  def to_s
    var
  end
end

huangapple
  • 本文由 发表于 2023年1月9日 19:41:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定