ruby 变量类型
There are 4 different types of variables in Ruby
. They are :
Ruby
有4种不同类型的变量。 他们是 :
Local Variables
局部变量
Class Variables
类变量
Instance Variables
实例变量
Global Variables
全局变量
Local | Global | Instance | Class | |
---|---|---|---|---|
Scope | Only within the block or a function | Throughout the program | Limited to one particular instance of a class | Limited to the class that they are defined in |
Naming | Local variables begin with a lowercase letter or _(underscore) | Global variables begin with $ | Instance variables begin with @ | Class variables begin with @@ |
Initialization | Not necessary to initialize. Using uninitialized local variable is interpreted as call to a method that has no arguments. | Not necessary to initialize. Uninitialized global variables have nil value. | Not necessary to initialize. Uninitialized instance variables have nil value. | Must be initialized before they are used. Using uninitialized class variable results in error. |
本地 | 全球 | 实例 | 类 | |
---|---|---|---|---|
范围 | 仅在块或功能内 | 整个程序 | 仅限于类的一个特定实例 | 限于它们在中定义的类 |
命名 | 局部变量以小写字母或_(下划线)开头 | 全局变量以$开头 | 实例变量以@开头 | 类变量以@@开头 |
初始化 | 无需初始化。 使用未初始化的局部变量被解释为对没有参数的方法的调用。 | 无需初始化。 未初始化的全局变量的值为nil。 | 无需初始化。 未初始化的实例变量的值为nil。 | 必须先初始化,然后再使用它们。 使用未初始化的类变量会导致错误。 |
翻译自: https://www.studytonight.com/ruby/types-of-variables-in-ruby
ruby 变量类型