在 Ruby 中修剪字串而不建立新字串
Stewart Nguyen
2022年5月18日

在 Ruby 中,我們可以使用 String#strip
方法來刪除空格。它會給你一個被修剪過的新字串。
另一方面,使用 bang 版本 strip!
將有助於避免建立新字串。
在 Ruby 中使用 strip!
修剪字串的方法
strip!
將從物件中刪除空格。如果不進行任何更改,它將返回 nil
。
' hello world '.strip!
輸出:
'hello world'
請避免分配 string = string.strip!
因為當未對字串進行任何更改時,這可能會導致意外結果。
string = 'hello world'
string = string.strip!
puts string
輸出:
nil