Ruby on rails 如何在Ruby中取消初始化/取消定义变量,这样我就不会';控制台中没有收到警告?
我在控制台中不断收到此警告,它正在干扰我的Ruby on rails 如何在Ruby中取消初始化/取消定义变量,这样我就不会';控制台中没有收到警告?,ruby-on-rails,ruby,variables,initialization,Ruby On Rails,Ruby,Variables,Initialization,我在控制台中不断收到此警告,它正在干扰我的输出,我希望它消失: d.rb:24: warning: previous definition of VariableA was here d.rb:86: warning: already initialized constant VariableA 在使用它们后尝试执行此操作: VariableA = nil VariableB = nil 重要提示:这些变量在循环中重复使用。在ruby中,每当您使用大写字母第一个字母时,您就是在创建一个常量。
输出,我希望它消失:
d.rb:24: warning: previous definition of VariableA was here
d.rb:86: warning: already initialized constant VariableA
在使用它们后尝试执行此操作:
VariableA = nil
VariableB = nil
重要提示:这些变量在循环中重复使用。在ruby中,每当您使用大写字母第一个字母时,您就是在创建一个常量。当它被重新定义时,您将收到警告
比如说
class
THIS_IS_A_CONSTANT = 42
ThisIsAlsoAConstant = "The answer!"
@@this_is_a_class_variable
def a_method
@this_is_a_member_variable = true
this_is_a_local_variable = true
end
end
如果在方法中创建常量,则第二次调用该方法时会出现重新定义错误。在ruby中,无论何时使用大写字母,第一个字母都是创建常量。当它被重新定义时,您将收到警告
比如说
class
THIS_IS_A_CONSTANT = 42
ThisIsAlsoAConstant = "The answer!"
@@this_is_a_class_variable
def a_method
@this_is_a_member_variable = true
this_is_a_local_variable = true
end
end
如果你在一个方法中创建了一个常量,那么在你第二次调用这个方法时就会出现重新定义错误。正如zhon所指出的,你实际上是在创建一个常量。defined?
关键字演示了这一点:
local_var = "foo"
some_constant = "bar"
Local_var = "foo"
SOME_CONSTAT = "baz"
puts defined? local_var #=> local-variable
puts defined? some_constant #=> local-variable
puts defined? Local_var #=> constant
puts defined? SOME_CONSTAT #=> constant
但是,不应创建初始大写的常量。约定是使用。正如zhon所指出的,您实际上是在创建一个常量。defined?
关键字演示了这一点:
local_var = "foo"
some_constant = "bar"
Local_var = "foo"
SOME_CONSTAT = "baz"
puts defined? local_var #=> local-variable
puts defined? some_constant #=> local-variable
puts defined? Local_var #=> constant
puts defined? SOME_CONSTAT #=> constant
但是,不应创建初始大写的常量。公约是要使用的