2

我想编写一种方法来修剪字符串末尾的字符。这很简单:

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

my_string = "Hello"
my_string = my_string.trim(1) # => Hell

我宁愿这是一种就地方法。天真的方法,

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

  def trim!(amount)
    self = trim(amount)
  end
end

抛出错误“无法更改 self 的值:self = trim(amount)”。

编写这种就地方法的正确方法是什么?我需要手动设置字符串的属性吗?如果是这样,我如何访问它们?

4

3 回答 3

4

您可以使用String#replace。所以它可以变成:

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

  def trim!(amount)
    replace trim(amount)
  end
end
于 2014-07-08T13:34:24.967 回答
1

使用String#[]=

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

s = 'asdf'
s.trim(2) # => "as"
s # => "as"
于 2014-07-08T13:32:39.613 回答
1

你可以写成

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

阅读String#sliceString#slice!

于 2014-07-08T13:33:52.797 回答