簡體   English   中英

在Ruby中實現Array的to_s

[英]Implement to_s of Array in Ruby

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所建議的那樣,可以避免胡鬧:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM