4
\$\begingroup\$

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            #=> "Hello World!"
puts str.trim       #=> "Hello World"
puts str.trim 7     #=> "Hello"
puts str            #=> "Hello World!"
puts str.trim!      #=> "Hello World"
puts str.trim! 6    #=> "Hello"
puts str            #=> "Hello"
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.