Question

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.

Was it helpful?

Solution

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top