Default values of Ruby variables

末鹿安然 提交于 2021-02-18 19:47:40

问题


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 a NameError:

    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 a NameError:

    defined? @@foo
    #=> nil
    
    @@foo
    # uninitialized class variable @@foo (NameError)
    
  • undefined constants raise a NameError:

    defined? FOO
    #=> nil
    
    FOO
    # uninitialized constant FOO (NameError)
    


来源:https://stackoverflow.com/questions/54548952/default-values-of-ruby-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!