如何检查变量是否存在没有“未定义的局部变量或方法”的值?

时间:2022-06-01 18:27:48

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

这是一种常见的模式:如果变量不存在,我会得到一个未定义的局部变量或方法错误。

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

现有代码有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.

我相信这有一个共同的模式/解决方案。

2 个解决方案

#1


22  

Change the present? to != '':

改变现在? to!='':

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

#2


1  

try :

尝试:

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

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

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

You can use only defined? to detect expired-session-hash, especially with deep level hash.

你只能使用定义?检测expired-session-hash,尤其是深层哈希。

if defined?(session[:user]['name'])
  puts "active session"
else
  puts "expired session"
end

#1


22  

Change the present? to != '':

改变现在? to!='':

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

#2


1  

try :

尝试:

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

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

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

You can use only defined? to detect expired-session-hash, especially with deep level hash.

你只能使用定义?检测expired-session-hash,尤其是深层哈希。

if defined?(session[:user]['name'])
  puts "active session"
else
  puts "expired session"
end