在 Ruby 中实现数组的 to_s
Implement to_s of Array in Ruby
Ruby的数组class有内置方法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 方法,以便 returns
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 所建议的,可以避免猴子路径:
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
更多 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
Ruby的数组class有内置方法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 方法,以便 returns
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 所建议的,可以避免猴子路径:
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
更多 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