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

时间:2013-03-22 16:28:36

标签: ruby monkeypatching

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

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

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


我试图自己解决这个问题,但是String的源代码在MRI中是C语言。

1 个答案:

答案 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"
相关问题