连接之前检查 nil 字符串
这个问题与很多问题类似,但绝不是重复的。这个问题是关于字符串连接和编写比检查 nil/zero 更好的代码。
目前我有:
file.puts "cn: " + (var1.nil? ? "UNKNOWN" : var1)
效果很好,但看起来不太好。在 ruby 中编写此代码的更好方法是什么,以便我检查 nil 而不是连接它
This question is similar to a LOT of questions, but in no such way is it anything of a duplicate. This question is about string concatenation and writing better code less than it is for checking nil/zero.
Currently I have:
file.puts "cn: " + (var1.nil? ? "UNKNOWN" : var1)
Which works fine, but doesn't look good. What is a better way to write this in ruby so that I am checking for nil and not concatenating it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以这样做:
或者,如果您愿意,也可以这样做:
或我最喜欢的,我认为这是最惯用的红宝石:
You can do this:
or, identically if you prefer:
or my favourite, which I think is the most idiomatic ruby:
使用
join
添加可能为nil
的字符串。如果存在
nil
,join
不会抱怨例如:
但是,如果您使用除空白字符串(例如下划线)之外的任何内容进行连接,您将得到一个 join String对于
nil
值:要解决此问题,请在加入之前使用
.compact
从Array
中删除nil
值:Use
join
to add the strings which may benil
.The
join
will not complain if there is anil
For example:
However, if you are joining with anything but a blank string, like an underscore, you will get a join String for the
nil
value:To fix this, use
.compact
to remove thenil
values from theArray
before joining:使用 ruby 2.4.1,
to_s
解析为nil
和"Hello"
。所以var1.to_s
应该足够了。Using ruby 2.4.1,
to_s
resolves for bothnil
and"Hello"
. Sovar1.to_s
should suffice.我会按照彼得的建议去做,假设
false
不是var1
的有效值,并且var1
保证为nil
或字符串。您还可以将该逻辑提取到函数中:仅当
var1
不能保证为 nil 或字符串时才需要to_s
。或者,如果您这样做:它将对
display_value
的结果执行隐式to_s
I would do what Peter suggested, assuming that
false
wasn't a valid value forvar1
, andvar1
was guaranteed to benil
or a string. You could also extract that logic into a function:to_s
is only necessary ifvar1
isn't guaranteed to be nil or a string. Alternatively, if you do:it will do an implicit
to_s
on the result ofdisplay_value
由于
"cn: "
部分纯粹是为了美观,因此(更多?)可能会发生变化以满足未来的演示指南,我建议使用 join;也许作为一个函数,如前所述 - 语义是相同的,只是方法名称/关键字发生了变化;
Since the
"cn: "
part is purely aesthetical and therefore (more?) subject to change to meet future presentation guidelines, I would recommend using join;Perhaps as a function, as mentioned earlier - semantics are the same, only method names/keywords have changed;