我想通过提供shuffle
和shuffle!
方法来monkeypatch Ruby的String类。
class String
def shuffle
self.split('').shuffle.join
end
end
返回一个新字符串。如何编写修改字符串而不是返回副本的shuffle!
方法?
我试图自己解决这个问题,但是String的源代码在MRI中是C语言。
答案 0 :(得分:9)
你不能分配给self
,这可能是我想到的第一件事。但是,有一个方便的方法String#replace
,你知道,它取代了字符串的内容。
class String
def shuffle
split('').shuffle.join
end
def shuffle!
replace shuffle
end
end
s = 'hello'
s.shuffle!
s # => "lhleo"