patternrubyMinor
Writing a safe class method in terms of a dangerous one
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:
The dangerous method,
How do I rewrite this so the safe method calls the dangerous method, without changing the functionality?
Sample output:
class String
def trim(amount=1)
self[0..-(amount+1)]
end
def trim!(amount=1)
self[0..-1] = trim(amount)
end
endThe 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
This returns the same sample output as above.
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
endThis 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
endContext
StackExchange Code Review Q#63881, answer score: 4
Revisions (0)
No revisions yet.