在 Ruby 中修剪字符串而不创建新字符串的规范方法是什么?
这就是我现在所拥有的——对于它正在做的工作来说,这看起来太冗长了。
@title = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil?
假设令牌是通过拆分 CSV 行获得的数组。现在像条一样的功能!咬!等。如果字符串没有被修改,全部返回 nil
"abc".strip! # => nil
" abc ".strip! # => "abc"
如果它包含额外的前导或尾随空格而不创建副本,Ruby 的方式是什么?
如果我想做就会变得更丑tokens[Title].chomp!.strip!
-
我猜你想要的是:
@title = tokens[Title] @title.strip!
如果它没有剥离任何东西,该
#strip!
方法将返回,如果它被剥离,则返回变量本身。nil
根据 Ruby 标准,以感叹号为后缀的方法会更改变量。
希望这可以帮助。
更新: 这是
irb
用于演示的输出:>> @title = "abc" => "abc" >> @title.strip! => nil >> @title => "abc" >> @title = " abc " => " abc " >> @title.strip! => "abc" >> @title => "abc"