Ruby 的 Array 类有内置方法 to_s 可以将数组转换为字符串。此方法也适用于多维数组。这个方法是如何实现的?
我想知道它,所以我可以重新实现一个方法 my_to_s(ary),它可以接收多维并将其转换为字符串。但不是像这样返回对象的字符串表示
[[[1,2,3, Person.new('Mary')]],[4,5,6,7], Person.new('Paul'),2,3,8].to_s
# [[[1, 2, 3, #<Person:0x283fec0 @name='Mary']], [4, 5, 6, 7], #<Person:0x283fe30 @name='Paul'>, 2, 3, 8]
my_to_s(ary) 应该在这些对象上调用 to_s 方法,以便它返回
my_to_s([[[1,2,3, Person.new('Mary')]],[4,5,6,7], Person.new('Paul'),2,3,8])
# [[[1, 2, 3, Student Mary]], [4, 5, 6, 7], Student Paul>, 2, 3, 8]
最佳答案
对于嵌套元素,它只是分别调用to_s
:
def my_to_s
case self
when Enumerable then '[' << map(&:my_to_s).join(', ') << ']'
else
to_s # or my own implementation
end
end
这是一个人为的例子,如果这个 my_to_s
方法是在 BasicObject
上定义的,它几乎可以工作。
正如 Stefan 所建议的,可以避免 monkeypathing:
def my_to_s(object)
case object
when Enumerable then '[' << object.map { |e| my_to_s(e) }.join(', ') << ']'
else
object.to_s # or my own implementation
end
end
更多面向对象的方法:
class Object
def my_to_s; to_s; end
end
class Enumerable
def my_to_s
'[' << map(&:my_to_s).join(', ') << ']'
end
end
class Person
def my_to_s
"Student #{name}"
end
end
关于ruby - 在 Ruby 中实现数组的 to_s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44649910/