在 Ruby 中使用安全导航
Ruby 安全导航运算符 (&.
) 是在 Ruby 2.3.0 中引入的。它允许你安全地链接对象上的方法,基本上是为了避免流行的 nil:NilClass 的未定义方法
错误。
本文将简要讨论如何在 Ruby 中使用安全导航。
在 Ruby 中使用安全导航来防止未定义的方法
示例代码:
class Bus
def seats
14
end
end
class Vehicle
def initialize(name)
@name = name
end
def category
Bus.new if @name == "hiace"
end
end
vehicle = Vehicle.new("camry")
number_of_seats = vehicle.category.seats
puts number_of_seats
输出:
undefined method `seats' for nil:NilClass (NoMethodError)
如上例所示,vehicle.category.seats
爆炸并导致 undefined method
错误,因为 vehicle.category
已经返回 nil
。为了避免这个问题,我们需要在链接另一个方法之前检查 vehicle.category
是否成功。
下一个示例,vehicle.category && vehicle.category.seats
表示如果 vehicle.category
成功,则应评估 vehicle.category.seats
,否则应停止代码执行并返回 nil
。这很好用,但可以用 Safe Navigation Operator 编写。
示例代码:
class Bus
def seats
14
end
end
class Vehicle
def initialize(name)
@name = name
end
def category
Bus.new if @name == "hiace"
end
end
vehicle = Vehicle.new("camry")
number_of_seats = vehicle.category && vehicle.category.seats
puts number_of_seats
输出:
nil
在最后一个示例中,我们将使用另一个更易读、更简洁的安全导航版本。它在我们必须在一个对象上链接许多方法的情况下变得很有用,例如 object1&.method1&.method2&.method3&.method4
。
示例代码:
class Bus
def seats
14
end
end
class Vehicle
def initialize(name)
@name = name
end
def category
Bus.new if @name == "hiace"
end
end
vehicle = Vehicle.new("camry")
number_of_seats = vehicle&.category&.seats
puts number_of_seats
输出:
nil
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。