如何编写将修改它的字符串monkeypatch方法

And*_*lov 4 ruby monkeypatching

我想通过提供shuffleshuffle!方法来monkeypatch Ruby的String类.

class String
  def shuffle
    self.split('').shuffle.join
  end
end
Run Code Online (Sandbox Code Playgroud)

它返回一个新字符串.如何编写shuffle!修改字符串而不是返回副本的方法?


我试图自己搞清楚,但String的源代码是在MRI中的C语言.

Ser*_*sev 9

你无法分配self,这可能是我想到的第一件事.但是,有一种方便的方法String#replace,你知道,它取代了字符串的内容.

class String
  def shuffle
    split('').shuffle.join
  end

  def shuffle!
    replace shuffle
  end
end

s = 'hello'
s.shuffle!
s # => "lhleo"
Run Code Online (Sandbox Code Playgroud)