问题
I need to know the default values of variables in ruby.
Global Variables: nil
Instance Variables: ?
Class Variables: ?
Local Variables: ?
I looked here, but all I could find is that global variables have a nil value.
回答1:
You assign a local variable value at first assignment:
local = 1
local1 + local # NameError: undefined local variable or method `local1' for main:Object
Class variables are similar, if you use them without initialization, you get an error:
class A
@@a
end
# NameError: uninitialized class variable @@a in A
Class instance variables and class variables are nil
by default:
class A
def self.a
@a
end
def a
@a
end
end
> A.a
#=> nil
> A.new.a
#=> nil
回答2:
This is trivial to test yourself:
undefined global variables evaluate to
nil
and generate a warning:defined? $foo #=> nil $foo #=> nil # warning: global variable `$foo' not initialized
undefined local variables
raise
aNameError
:defined? foo #=> nil foo # undefined local variable or method `foo' for main:Object (NameError)
defined but not initialized local variables evaluate to
nil
:defined? foo #=> nil if false then foo = 42 end defined? foo #=> 'local-variable' foo #=> nil
undefined instance variables evaluate to
nil
and generate a warning:defined? @foo #=> nil @foo #=> nil # warning: instance variable `@foo' not initialized
undefined class variables
raise
aNameError
:defined? @@foo #=> nil @@foo # uninitialized class variable @@foo (NameError)
undefined constants
raise
aNameError
:defined? FOO #=> nil FOO # uninitialized constant FOO (NameError)
来源:https://stackoverflow.com/questions/54548952/default-values-of-ruby-variables