Search code examples
rubystringin-place

How to write an in-place method for strings


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?


Solution

  • Using String#[]=

    class String
      def trim(amount)
        self[0..-1] = self[0..-(amount+1)]
      end
    end
    
    s = 'asdf'
    s.trim(2) # => "as"
    s # => "as"