这就是我现在得到的——对于它正在做的工作来说,这看起来太啰嗦了。

@title        = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil?

假设token是通过分割CSV行获得的数组。 现在的功能像脱衣!chomp !如果字符串未被修改,则返回nil

"abc".strip!    # => nil
" abc ".strip!  # => "abc"

如果它包含额外的前导空格或尾随空格,Ruby如何在不创建副本的情况下对其进行修剪?

如果我想要做令牌[Title].chomp!.strip!


我猜你想要的是:

@title = tokens[Title]
@title.strip!

#地带!如果没有剥离任何内容,方法将返回nil,如果已剥离,则返回变量本身。

根据Ruby标准,带有感叹号后缀的方法会就地更改变量。

更新:这是从irb输出演示:

>> @title = "abc"
=> "abc"
>> @title.strip!
=> nil
>> @title
=> "abc"
>> @title = " abc "
=> " abc "
>> @title.strip!
=> "abc"
>> @title
=> "abc"

我认为你的例子是一个明智的方法,尽管你可以稍微简化一下:

@title = tokens[Title].strip! || tokens[Title] if tokens[Title]

或者你可以把它放在两行:

@title = tokens[Title] || ''
@title.strip!

没有必要同时strip和chomp,因为strip也会删除尾随回车符——除非你改变了默认的记录分隔符,而这就是你正在咀嚼的。

Olly的回答已经在Ruby中有了规范的方法,尽管如果你发现自己经常这样做,你总是可以为它定义一个方法:

def strip_or_self!(str)
  str.strip! || str
end

给:

@title = strip_or_self!(tokens[Title]) if tokens[Title]

还要记住,如果令牌为nil, if语句将阻止@title被赋值,这将导致它保持之前的值。如果你想要或不介意@title总是被分配,你可以将检查移动到方法中,进一步减少重复:

def strip_or_self!(str)
  str.strip! || str if str
end

作为一种选择,如果你有冒险精神,你可以在String本身定义一个方法:

class String
  def strip_or_self!
    strip! || self
  end
end

给予其中之一的:

@title = tokens[Title].strip_or_self! if tokens[Title]

@title = tokens[Title] && tokens[Title].strip_or_self!

顺便说一下,现在红宝石已经支持只是剥离没有“!”

比较:

p "abc".strip! == " abc ".strip!  # false, because "abc".strip! will return nil
p "abc".strip == " abc ".strip    # true

而且,没有副本是不可能脱衣的。参见string.c中的源代码:

static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}

Ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

更新1: 就像我现在看到的,它是在1999年创建的(参见SVN中的rev #372):

更新2: 带!不会在1.9中创建副本。x, 2。X和trunk版本。


我的方法:

> (@title = " abc ").strip!
 => "abc" 
> @title
 => "abc" 

@title = tokens[Title].strip! || tokens[Title]

我完全有可能听不懂这个话题,但这不正是你所需要的吗?

" success ".strip! || "rescue" #=> "success"
"failure".strip! || "rescue" #=> "rescue"

如果你有ruby 1.9或active支持,你可以简单地做

@title = tokens[Title].try :tap, &:strip!

这真的很酷,因为它利用了:try和:tap方法,在我看来,这是ruby中最强大的函数结构。

一种更可爱的形式,将功能全部传递为符号:

@title = tokens[Title].send :try, :tap, &: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"

如果你想使用另一种方法,你需要这样的东西:

( str.strip || str ).split(',')

这样你就可以脱光衣服,之后还能做点什么:)