英文:
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("content")
puts obj # Prints #<MyClass:0x0000011fce07b4a0> but I want it to print "content"
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("content")
puts obj # Prints "content"
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论