[英]Implement to_s of Array in Ruby
Ruby's Array class has the built-in method to_s that can turn the array into a string. Ruby的Array类具有内置方法to_s,该方法可以将数组转换为字符串。 This method also works with multidimensional array.
此方法也适用于多维数组。 How is this method implemented?
如何实现此方法?
I want to know about it, so I can reimplement a method my_to_s(ary) that can take in a multidimensional and turn it to a string. 我想知道这一点,所以我可以重新实现方法my_to_s(ary) ,该方法可以采用多维并将其转换为字符串。 But instead of returning a string representation of the object like this
但是不要像这样返回对象的字符串表示形式
[[[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) should call the to_s method on these objects, so that it returns 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]
For nested elements it just calls to_s
respectively: 对于嵌套元素,它仅分别调用
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
This is a contrived example, that nearly works, if this my_to_s
method is defined on the very BasicObject
. 这是一个人为的例子,近工作,如果这个
my_to_s
方法上非常明确的BasicObject
。
As suggested by Stefan, one might avoid monkeypathing: 正如Stefan所建议的那样,可以避免胡闹:
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
More OO approach: 更多OO方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.