使用大于号的 Ruby 安全运算符

ste*_*och 6 ruby

我试图弄清楚如何在以下场景中使用 Ruby 的安全运算符:

if attribute_value && attribute_value.length > 255
Run Code Online (Sandbox Code Playgroud)

如果 attribute_value 为零,则以下内容不起作用:

if attribute_value&.length > 255

# NoMethodError: undefined method `>' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

我明白为什么,但我想知道如何解决这个问题。以下工作,但它是丑陋的地狱:

if attribute_value&.(length > 255)
Run Code Online (Sandbox Code Playgroud)

这样做的推荐方法是什么?我想我可以做到以下几点:

if attribute_value&.length.to_i > 255
Run Code Online (Sandbox Code Playgroud)

对于这种情况,这还不错。还要别的吗?

And*_*rtz 5

作为对所问问题的直接回答,您可以直接使用安全导航运算符,因为x > y它实际上只是在对象 x 上调用> 方法。也就是说,x > yx.>(y)x.send(:>, y)

因此,您可以使用x&.> y. 或者,在你的情况下,attribute_value&.length&.> 255

就个人而言,我更喜欢attribute_value && attribute_value.length > 255,但也许这只是我。


tad*_*man 2

这类事情取决于您试图容纳哪种类型的缺失值,如果无法定义它,则与在边界内或边界外相同。

您的做法:

attribute_value&.length.to_i > 255
Run Code Online (Sandbox Code Playgroud)

只要nil意思是“不超出界限”,似乎就足够合理了。

我经常用如下的防护条件来处理这个问题:

return unless attribute_value

if attribute_value.length > 255
  # ... Handle condition
end
Run Code Online (Sandbox Code Playgroud)