Ruby 如何为字符串编写就地方法

Ruby 如何为字符串编写就地方法,ruby,string,in-place,Ruby,String,In Place,我想写一个从字符串末尾修剪字符的方法。这很简单,可以做到: 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

我想写一个从字符串末尾修剪字符的方法。这很简单,可以做到:

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)的值”

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

使用

你可以写成

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
阅读和

您可以使用的。因此,它可以成为:

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

  def trim!(amount)
    replace trim(amount)
  end
end

“你好”。trim(1)应该返回“Hell”@DevonParsons我正在自定义你的代码。。那一次它消失了。。我没有注意到…-)那是个打字错误。我修正了。我收到的所有答案都很棒,我接受@falsetru的答案,因为它最接近我的初衷。我将修改它以同时包含trim()和trim!(),但原则是正确的。答案很好,但请注意,
trim
replace trim(amount)
就足够了。@CarySwoveland fair call-在编写实例方法时,我总是有点
self
困扰:)
class String
  def trim(amount)
    self[0..-(amount+1)]
  end

  def trim!(amount)
    replace trim(amount)
  end
end