如果我不向函数传递任何内容,Ruby 可以检查 'nil' 吗?
Can Ruby check 'nil' if I pass nothing into a function?
我的助手有这种奇怪的行为,怀疑与 Is Ruby pass by reference or by value? 有关,我可以请你帮忙解释一下这种行为吗?
views/xxx.html
helperA(@object.attribute_A)
helperA.rb
def helperA(object)
if object == nil
return
end
# do something if not nil
然而,当没有任何东西被传递到 helper 时(对象没有 attribute_A),'if object == nil' 没有捕捉到这种情况并继续 运行 代码,这通常会导致像“undefined method `length' for nil:NilClass”这样的错误,这是因为 helper.
后面的操作
我的问题是为什么会这样?
# set object to default as nil
def helperA(object = nil)
return nil if object.nil? ## use object.blank? if you want empty strings, empty hashes and empty arrays to be caught in addition to nil
# do something if not nil
end
您还可以对传递给输入的内容进行处理
helperA(@object&.attribute_A) # tells the function to treat the input as nil if the @object doesn't exist
我的助手有这种奇怪的行为,怀疑与 Is Ruby pass by reference or by value? 有关,我可以请你帮忙解释一下这种行为吗?
views/xxx.html
helperA(@object.attribute_A)
helperA.rb
def helperA(object)
if object == nil
return
end
# do something if not nil
然而,当没有任何东西被传递到 helper 时(对象没有 attribute_A),'if object == nil' 没有捕捉到这种情况并继续 运行 代码,这通常会导致像“undefined method `length' for nil:NilClass”这样的错误,这是因为 helper.
后面的操作我的问题是为什么会这样?
# set object to default as nil
def helperA(object = nil)
return nil if object.nil? ## use object.blank? if you want empty strings, empty hashes and empty arrays to be caught in addition to nil
# do something if not nil
end
您还可以对传递给输入的内容进行处理
helperA(@object&.attribute_A) # tells the function to treat the input as nil if the @object doesn't exist