How to write a String monkeypatch method that will change it

I want the monkeypatch Ruby String class to provide shuffle and shuffle! methods shuffle! .

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

Returns a new line. How to write a shuffle! method shuffle! which modifies the string instead of returning a copy?


I tried to figure it out myself, but the String source code is in C in the MRI.

+4
source share
1 answer

You cannot assign self , which is probably the first thing that comes to mind. However, there is a convenient String#replace method, which, as you know, replaces the contents of a string.

 class String def shuffle split('').shuffle.join end def shuffle! replace shuffle end end s = 'hello' s.shuffle! s # => "lhleo" 
+9
source

All Articles