Writing a safe class method in terms of a dangerous one I commonly need to trim characters from the end of a string (when building SQL queries, I have trailing commas, brackets, even words sometimes), so I wrote the following:

class String
  def trim(amount=1)
    self[0..-(amount+1)]
  end

  def trim!(amount=1)
    self[0..-1] = trim(amount)
  end
end


The dangerous method, trim!, calls the safe method, trim. According to the Ruby Style Guide, this is backwards.

How do I rewrite this so the safe method calls the dangerous method, without changing the functionality?

Sample output:


str = "Hello World!"
puts str            #=&gt; "Hello World!"
puts str.trim       #=&gt; "Hello World"
puts str.trim 7     #=&gt; "Hello"
puts str            #=&gt; "Hello World!"
puts str.trim!      #=&gt; "Hello World"
puts str.trim! 6    #=&gt; "Hello"
puts str            #=&gt; "Hello"
As hinted to in the Ruby Style Guide, the Object#dup method returns a duplicate of self to be passed to other methods without danger of altering self. The solution is as simple as moving the trim logic into the trim! function and having trim call dup.trim!

class String
  def trim!(amount=1)
    self[0..-1] = self[0..-(amount+1)]
  end

  def trim(amount=1)
    dup.trim! amount
  end
end


This returns the same sample output as above.