Ruby 在调用方法之前检查是否为 nil [英] Ruby check if nil before calling method
问题描述
我在 Ruby 中有一个字符串,我在该字符串上调用 strip 方法来删除前导和尾随空格.例如
I have a string in Ruby on which I'm calling the strip method to remove the leading and trailing whitespace. e.g.
s = "12345 "
s.strip
但是,如果字符串是 empty nil
我得到以下错误.
However if the string is empty nil
I get the following error.
NoMethodError: undefined method `strip' for nil:NilClass
我使用的是 Ruby 1.9,那么在调用 strip 方法之前检查值是否为 nil
的最简单方法是什么?
I'm using Ruby 1.9 so whats the easiest way to check if the value is nil
before calling the strip method?
更新:
我在数组中的一个元素上尝试过这个,但遇到了同样的问题:
I tried this on an element in an array but got the same problem:
data[2][1][6].nil? ? data[2][1][6] : data[2][1][6].split(":")[1].strip
推荐答案
Ruby 2.3.0 添加了一个安全导航操作符 (&.
),在调用之前检查 nil方法.
Ruby 2.3.0 added a safe navigation operator (&.
) that checks for nil before calling a method.
s&.strip
如果 s
是 nil
,这个表达式返回 nil
而不是引发 NoMethodError
.
If s
is nil
, this expressions returns nil
instead of raising NoMethodError
.
这篇关于Ruby 在调用方法之前检查是否为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!