如何将删除字符应用于字符串本身?

How do I apply removing of characters to the string itself?

使用Ruby 2.4。我如何将对 stirng 的编辑应用到字符串本身?我有这个方法

  # Removes the word from teh end of the string
  def remove_word_from_end_of_str(str, word)
    str[0...(-1 * word.length)]
  end

我想对参数进行操作,但它不起作用...

2.4.0 :001 > str = "abc def"
 => "abc def"
2.4.0 :002 > StringHelper.remove_word_from_end_of_str(str, "def")
 => "abc "
2.4.0 :003 > str
 => "abc def"

我希望传入的字符串等于 "abc ",但这并没有发生。我不想将变量设置为函数的结果(例如 "str = StringHelper.remove(...)"

str[range] 只是 str.slice(range) 的 shorthand。你只需要使用破坏性的方法,就像那样:

# Removes the word from the end of the string
def remove_word_from_end_of_str(str, word)
    str.slice!((str.length - word.length)...(str.length))
end

有关详细信息,请参阅 the documentation

如果您希望您的函数也 return 新字符串,您应该使用 :

# Removes the word from the end of the string
def remove_word_from_end_of_str(str, word)
    str.slice!((str.length - word.length)...(str.length))
    str
end

Ruby 已经有 String#delete! 方法可以做到这一点:

>> str = 'abc def'
=> "abc def"
>> word = 'def'
=> "def"
>> str.delete!(word)
=> "abc "
>> str
=> "abc "

请注意,这将删除 word:

的所有实例
>> str = 'def abc def'
=> "def abc def"
>> str.delete!(word)
=> " abc "

要将效果限制在最后一个字,您可以这样做:

>> str = 'def abc def'
=> "def abc def"
>> str.slice!(-word.length..-1)
=> "def"
>> str
=> "def abc "

尝试:

def remove_word_from_end_of_str(str, word)
    str.slice!((str.length - word.length)..str.length)
end

另外,你的解释有点混乱。您将 remove_word 方法作为 class 方法调用,但它是一个实例方法。

chomp! returns 从字符串末尾删除给定记录分隔符的字符串(如果存在),如果未删除任何内容,则 nil

def remove_word_from_end_of_str(str, word)
  str.chomp!( "CO")
end

str = "Aurora CO" 
remove_word_from_end_of_str(str, "CO")
p str  #=> "Aurora "