I'd want to monkeypatch Ruby's String class by providing shuffle
and shuffle!
methods.
class String
def shuffle
self.split('').shuffle.join
end
end
It returns a new string. How can I write a shuffle!
method that modifies string instead of returning copy?
I tried to figure it out by myself but String's source code is in C in MRI.
You can't assign to self
, which is probably the first thing that comes to mind. However, there's a convenient method String#replace
, which, you know, replaces string's content.
class String
def shuffle
split('').shuffle.join
end
def shuffle!
replace shuffle
end
end
s = 'hello'
s.shuffle!
s # => "lhleo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With