代码之家  ›  专栏  ›  技术社区  ›  stephenmurdoch

使用具有大于

  •  1
  • stephenmurdoch  · 技术社区  · 7 年前

    我正在尝试在以下场景中使用Ruby的安全操作符:

    if attribute_value && attribute_value.length > 255
    

    如果属性_值为nil,则以下操作无效:

    if attribute_value&.length > 255
    
    # NoMethodError: undefined method `>' for nil:NilClass
    

    我知道为什么,但我想知道的是我该如何度过这个难关。以下方法很管用,但非常难看:

    if attribute_value&.(length > 255)
    

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

    if attribute_value&.length.to_i > 255
    

    这对这种情况来说还不错。还有别的吗?

    0 回复  |  直到 7 年前
        1
  •  8
  •   Andrew Schwartz    7 年前

    作为对所问问题的直接回答,您可以直接使用安全导航操作员 x > y 真的只是打电话给 > method 在物体x上,也就是说, x>Y 和 x.>(y) 或 x.send(:>, y)

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

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

        2
  •  1
  •   tadman    7 年前

    这类事情取决于您试图容纳的缺失值的类型,以及未能定义它是否与在范围内或范围外相同。

    你的方法是:

    attribute_value&.length.to_i > 255
    

    只要 nil 意思是“不越界”。

    我通常会在以下情况下处理:

    return unless attribute_value
    
    if attribute_value.length > 255
      # ... Handle condition
    end
    
    推荐文章