将空字符串就地转换为nil?

问题描述 投票:0回答:4

我正在寻找一种使用 Ruby 将空字符串转换为

nil
的方法。如果我最终得到的字符串是空的,我可以这样做

 "    ".strip!

这会给我空字符串

""

我希望能够做的就是这样的事情。

"    ".strip!.to_nil!

这将用

nil
就地替换空字符串。如果字符串是
to_nil!
,则直接将字符串更改为
nil
,否则如果字符串不为空,则不会更改。
这里的关键是我希望它直接发生,而不是通过诸如

之类的分配

.empty?


ruby string null in-place
4个回答
79
投票
f = nil if f.strip!.empty?

我们来测试一下。

presence

请注意此方法来自 Ruby on Rails v4.2.7
https://apidock.com/rails/Object/presence


4
投票

' '.presence # => nil ''.presence # => nil 'text'.presence # => "text" nil.presence # => nil [].presence # => nil {}.presence # => nil true.presence # => true false.presence # => nil

可以就地工作,因为可以修改原始对象来存储新值。但值

String#squeeze!
是不同类的对象,因此它不能用
String
类的对象表示。


3
投票

nil

然后你会得到:

class String def to_nil present? ? self : nil end end

当然,您也可以在检查是否适合您之前先剥掉绳子


1
投票
'a'.to_nil => "a" ''.to_nil => nil

,如果匹配则返回

string[regexp]
,如果正则表达式不匹配则返回
new_string
(请参阅文档
String
)。 nil

© www.soinside.com 2019 - 2024. All rights reserved.