Ruby-on-rails 如何在没有“未定义的局部变量或方法”的情况下检查变量是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12110235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:41:10  来源:igfitidea点击:

How to check if a variable exists with a value without "undefined local variable or method"?

ruby-on-railsrubyvariablesundefinedexists

提问by Michael Durrant

This is a common pattern: If a variable doesn't exist I get an undefined local variable or methoderror.

这是一个常见的模式:如果变量不存在,我会收到undefined local variable or method错误消息。

The existing code has if variable_name.present?but this didn't account for the variable not existing.

现有代码有,if variable_name.present?但这并没有考虑到不存在的变量。

How can I check the value of the variable and also account for it not existing at all?

如何检查变量的值并说明它根本不存在?

I've tried:

我试过了:

if (defined? mmm) then
  if mmm.present? then
    puts "true"
  end
end

but Ruby still checks that inner mmm.present?and throws "no such variable" when it doesn't exist.

但是 Ruby 仍然会检查内部mmm.present?并在它不存在时抛出“没有这样的变量”。

I'm sure there's a common pattern/solution to this.

我确信对此有一个共同的模式/解决方案。

回答by Michael Durrant

Change the present?to != ''and use the && operator which only tries to evaluate the seond expression if the first one is true:

更改present?to!= ''并使用 && 运算符,如果第一个表达式为真,它只会尝试评估第二个表达式:

if defined?(mmm) && (mmm != '') then puts "yes" end

But actually as of 2019 this is no longer needed as both the below work

但实际上从 2019 年开始,这不再需要,因为下面的工作

irb(main):001:0> if (defined? mm) then
irb(main):002:1* if mm.present? then
irb(main):003:2* p true
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> if (defined? mm) then
irb(main):007:1* p mm
irb(main):008:1> end
=> nil

回答by Komsun K.

On Ruby on Rails

在 Ruby on Rails 上

if defined?(mm) && mm.present?
  puts "acceptable variable"
end

On IRB

在 IRB 上

if defined?(mm) && !mm.blank? && !mm.nil?
  puts "acceptable variable"
end

It can make sure you won't get undefined variable or nil or empty value.

它可以确保您不会得到未定义的变量或 nil 或空值。