Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write String monkeypatch method that will modify it

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.

like image 525
Andrei Botalov Avatar asked Jan 13 '23 21:01

Andrei Botalov


1 Answers

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"
like image 62
Sergio Tulentsev Avatar answered Jan 16 '23 11:01

Sergio Tulentsev