将空字符串转换为 nil 就地? [英] Converting an empty string to nil in place?

查看:68
本文介绍了将空字符串转换为 nil 就地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用 Ruby 将空字符串转换为 nil 的方法.如果我最终得到一个空格的字符串,我可以做

 "".带!

这会给我一个空字符串"".

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

<代码>"".strip!.to_nil!

这将使用 nil 就地替换空字符串.to_nil! 如果是.empty? 直接把字符串改成nil 否则如果字符串不为空就不会改变.>

这里的关键是我希望它直接发生,而不是通过诸如

f = nil 如果 f.strip!.empty?

解决方案

干净的方法是使用 presence.

让我们测试一下.

' '.presence# =>零''.在场# =>零'文本'.存在# =>文本"零存在# =>零[].在场# =>零{}.在场# =>零真实存在# =>真的假存在# =>零

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

I'm looking for a way to convert an empty string to nil in place using Ruby. If I end up with a string that is empty spaces I can do

 "    ".strip!

This will give me the empty string "".

What I would like to be able to do is something like this.

"    ".strip!.to_nil!

This will get an in place replacement of the empty string with nil. to_nil! would change the string to nil directly if it is .empty? otherwise if the string is not empty it would not change.

The key here is that I want it to happen directly rather than through an assignment such as

f = nil if f.strip!.empty?

解决方案

The clean way is using presence.

Let's test it.

'    '.presence
# => nil


''.presence
# => nil


'text'.presence
# => "text"


nil.presence
# => nil


[].presence
# => nil


{}.presence
# => nil

true.presence
# => true

false.presence
# => nil

Please note this method is from Ruby on Rails v4.2.7 https://apidock.com/rails/Object/presence

这篇关于将空字符串转换为 nil 就地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆