关于 Ruby on Rails
if defined?(mm) && mm.present?
puts "acceptable variable"
end
在 IRB 上
if defined?(mm) && !mm.blank? && !mm.nil?
puts "acceptable variable"
end
它可以确保您不会得到未定义的变量或 nil 或空值。
了解如何defined?
运作
a = 1
defined?(a) # => "local-variable"
b = nil
defined?(b) # => "local-variable"
c = ""
defined?(c) # => "local-variable"
d = []
defined?(d) # => "local-variable"
$e = 'text'
defined?($e) # => "global-variable"
defined?(f) # => nil
defined?($g) # => nil
请注意,defined?
检查范围内的变量。
为什么你需要defined?
当可能存在未定义的变量时,您不能仅使用示例检查它.nil?
,您将有机会获得 NameError。
a = nil
a.nil? # => true
b.nil? # => NameError: undefined local variable or method `b'