我编写了一个类,它的作用类似于另一个类的数组。我有一个 to_s 方法,当按如下方式使用时,它以类似于数组的方式返回:
array = [1, 2, 3, 4]
puts array
这导致输出:
1
2
3
4
与字符串插值一起使用时 puts "#{array}"
输出不同:
[1, 2, 3, 4]
我如何在我的类中实现一个 to_s 方法,以便在字符串插值中不使用它时提供多行输出,在字符串插值中使用时提供单行输出?
我考虑尝试使用 caller_locations(1,1)[0].label
获取调用者标签,但这似乎远非最佳。对相关文档的任何帮助或指导将不胜感激,我还没有找到关于这个主题的任何内容。谢谢!
最佳答案
Array#to_s
不会(也不应该)检查调用它的上下文。数组的打印方式不同,因为 puts
检查给定的参数是否是一个数组(或可以转换为数组)。来自documentation :
If called with an array argument, writes each element on a new line.
你可以提供一个to_ary
方法:
class MyArray
def to_s
[1, 2, 3].join('-')
end
def to_ary
[1, 2, 3]
end
end
a = MyArray.new
puts a # calls to_ary and then prints each item on a separate line
# 1
# 2
# 3
puts a.to_s # just prints the result of to_s
# 1-2-3
puts "#{a}" # same as above
# 1-2-3
关于ruby - 如何从字符串插值语法的类 to_s 方法中获得不同的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42996471/