这就是我现在得到的——对于它正在做的工作来说,这看起来太啰嗦了。
@title = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil?
假设token是通过分割CSV行获得的数组。
现在的功能像脱衣!chomp !如果字符串未被修改,则返回nil
"abc".strip! # => nil
" abc ".strip! # => "abc"
如果它包含额外的前导空格或尾随空格,Ruby如何在不创建副本的情况下对其进行修剪?
如果我想要做令牌[Title].chomp!.strip!
如果你使用的是Ruby on Rails,就会有一个问题
> @title = " abc "
=> " abc "
> @title.squish
=> "abc"
> @title
=> " abc "
> @title.squish!
=> "abc"
> @title
=> "abc"
如果你只使用Ruby,你想使用strip
这就是问题所在。在你的情况下,你想使用脱衣没有爆炸!
而地带!当然会返回nil,如果没有动作,它仍然会更新变量,所以strip!不能内联使用。如果你想使用带内联,你可以使用版本没有bang !
带!使用多线方法
> tokens["Title"] = " abc "
=> " abc "
> tokens["Title"].strip!
=> "abc"
> @title = tokens["Title"]
=> "abc"
条形单线进场…你的答案
> tokens["Title"] = " abc "
=> " abc "
> @title = tokens["Title"].strip if tokens["Title"].present?
=> "abc"
如果你有ruby 1.9或active支持,你可以简单地做
@title = tokens[Title].try :tap, &:strip!
这真的很酷,因为它利用了:try和:tap方法,在我看来,这是ruby中最强大的函数结构。
一种更可爱的形式,将功能全部传递为符号:
@title = tokens[Title].send :try, :tap, &:strip!