Reputation: 1288
I want to write a method to trim characters from the end of a string. This is simple enough to do:
class String
def trim(amount)
self[0..-(amount+1)]
end
end
my_string = "Hello"
my_string = my_string.trim(1) # => Hell
I would rather have this be an in-place method. The naive approach,
class String
def trim(amount)
self[0..-(amount+1)]
end
def trim!(amount)
self = trim(amount)
end
end
throws the error "Can't change the value of self: self = trim(amount)".
What is the correct way of writing this in-place method? Do I need to manually set the attributes of the string? And if so, how do I access them?
Upvotes: 2
Views: 729
Reputation: 9649
You can use String#replace. So it could become:
class String
def trim(amount)
self[0..-(amount+1)]
end
def trim!(amount)
replace trim(amount)
end
end
Upvotes: 4
Reputation: 118261
You can write as
class String
def trim(amount)
self.slice(0..-(amount+1))
end
def trim!(amount)
self.slice!(-amount..-1)
self
end
end
my_string = "Hello"
puts my_string.trim(1) # => Hell
puts my_string # => Hello
my_string = "Hello"
puts my_string.trim!(1) # => Hell
puts my_string # => Hell
Read the String#slice
and String#slice!
Upvotes: 1
Reputation: 368904
Using String#[]=
class String
def trim(amount)
self[0..-1] = self[0..-(amount+1)]
end
end
s = 'asdf'
s.trim(2) # => "as"
s # => "as"
Upvotes: 1