2013-03-22 64 views
4

我愿意通过提供shuffleshuffle!方法猴补丁Ruby的String类。如何写字符串猴补丁的方法,将修改它

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

它返回一个新的字符串。我怎样才能写一个shuffle!方法来修改字符串而不是返回复制?


我尝试自己看着办吧,但串的源代码是在C语言中MRI。

回答

9

您不能分配到self,这可能是我想到的第一件事。但是,有一种方便的方法String#replace,您知道它会替换字符串的内容。

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

    def shuffle! 
    replace shuffle 
    end 
end 

s = 'hello' 
s.shuffle! 
s # => "lhleo"