我想写一个方法来修剪字符串末尾的字符。这很简单:
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/