HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Writing a safe class method in terms of a dangerous one

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodwritingonesafedangeroustermsclass

Problem

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"

Solution

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.

Code Snippets

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

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

Context

StackExchange Code Review Q#63881, answer score: 4

Revisions (0)

No revisions yet.