2017-06-20 64 views
0

Ruby的Array類具有內置方法to_s,可將數組轉換爲字符串。該方法也適用於多維數組。這個方法如何實現?在Ruby中實現to_s的數組to_lod

我想知道它,所以我可以重新實現方法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(進制)應該調用這些對象的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] 
+1

我真的認爲你只是想重寫'人#to_s '返回''Student#{self.name}「'字符串。 – mudasobwa

回答

2

對於嵌套元素它只是調用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上定義。


正如斯蒂芬建議,人們可能會避免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 
+2

或'object.map {| o | my_to_s(o)}'以避免猴子補丁。 – Stefan

+0

而且你可能想要用''[''和'']''環繞嵌套的輸出。 – Stefan

+0

@Stefan確實,謝謝,我已經更新了答案(對於monkeypatched版本和外部方法)。 – mudasobwa