Ruby变量的默认值

时间:2019-02-06 08:00:31

标签: ruby variables

我需要知道ruby中变量的默认值。

Global Variables: nil
Instance Variables: ? 
Class Variables: ?
Local Variables: ?

我看了here,但我能发现的是全局变量的值为nil。

2 个答案:

答案 0 :(得分:2)

您在首次分配时分配了局部变量值:

local = 1
local1 + local # NameError: undefined local variable or method `local1' for main:Object

类变量相似,如果不进行初始化就使用它们,则会出现错误:

class A
  @@a
end  
# NameError: uninitialized class variable @@a in A

类实例变量和类变量默认为nil

class A
  def self.a
    @a
  end  
  def a
    @a
  end  
end  

> A.a
#=> nil
> A.new.a
#=> nil

答案 1 :(得分:0)

测试自己很简单:

  • 未定义的全局变量的计算结果为nil并生成警告:

    defined? $foo
    #=> nil
    
    $foo
    #=> nil
    # warning: global variable `$foo' not initialized
    
  • 未定义的局部变量raiseNameError

    defined? foo
    #=> nil
    
    foo
    # undefined local variable or method `foo' for main:Object (NameError)
    
  • 已定义但未初始化的局部变量的求值为nil

    defined? foo
    #=> nil
    
    if false then foo = 42 end
    
    defined? foo
    #=> 'local-variable'
    
    foo
    #=> nil
    
  • 未定义的实例变量的值为nil并生成警告:

    defined? @foo
    #=> nil
    
    @foo
    #=> nil
    # warning: instance variable `@foo' not initialized
    
  • 未定义的类变量raiseNameError

    defined? @@foo
    #=> nil
    
    @@foo
    # uninitialized class variable @@foo (NameError)
    
  • 未定义的常量raiseNameError

    defined? FOO
    #=> nil
    
    FOO
    # uninitialized constant FOO (NameError)
    
相关问题