是否有更好的方法来检查 Ruby 中字符串的 Nil 或 Length == 0? [英] Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?
本文介绍了是否有更好的方法来检查 Ruby 中字符串的 Nil 或 Length == 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有比以下更好的方法来检查字符串是否为零或在 Ruby 中的长度为 0?
Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?
if !my_string || my_string.length == 0
return true
else
return false
end
在 C# 中很方便
string.IsNullOrEmpty(myString)
有什么类似于 Ruby 的东西吗?
Anything similar to that in Ruby?
推荐答案
当我不担心性能时,我会经常使用这个:
When I'm not worried about performance, I'll often use this:
if my_string.to_s == ''
# It's nil or empty
end
当然有各种变化......
There are various variations, of course...
if my_string.to_s.strip.length == 0
# It's nil, empty, or just whitespace
end
这篇关于是否有更好的方法来检查 Ruby 中字符串的 Nil 或 Length == 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文