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

标签 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 trim!(amount)
    self = trim(amount)
  end
end

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

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

最佳答案

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

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

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

关于ruby - 如何为字符串编写就地方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24633119/

相关文章:

ruby - 未初始化的常量生成器 (NameError) - Ruby

ruby - 正则表达式不匹配带括号的新行

ruby - 在 Sinatra 应用程序中维护单一、持久的 EM 连接

C strcmp - 比较由 char 和 char* 声明的字符串

java - 将行数据读取到字符串数组中?

ruby-on-rails - ruby 中的方法不会改变变量

c++ - 是否可以在 C++ 中增加变量范围?

python - 修改 Python 列表中的一个元素时出错

java - 就地快速排序

python - 运行时错误 : one of the variables needed for gradient computation has been modified by an inplace operation