红宝石 |变量类型
Ruby 中有不同类型的变量:
- 局部变量
- 实例变量
- 类变量
- 全局变量
Ruby 中的每个变量都是通过在变量名的开头使用特殊字符来声明的,如下表所述:
Symbol | Type of Variable |
---|---|
[a-z] or _ | Local Variable |
@ | Instance Variable |
@@ | Class Variable |
$ | Global Variable |
局部变量:局部变量名称始终以小写字母 (az) 或下划线 (_) 开头。这些变量对于声明它们的代码结构是本地的。局部变量只能在其初始化块内访问。局部变量在方法之外不可用。不需要初始化局部变量。
例子:
age = 10
_Age = 20
实例变量:实例变量名称总是以@符号开头。它们类似于类变量,但它们的值对于对象的特定实例是局部的。实例变量在任何指定实例或对象的方法中都可用,即实例变量可以从一个对象更改为另一个对象。不需要初始化实例变量,未初始化的实例变量总是包含一个nil值。
例子:
#!/usr/bin/ruby
# Ruby program to illustrate
# the Instance Variables
class Customer
def initialize(id, name, addr)
# Instance Variables
@cust_id = id
@cust_name = name
@cust_addr = addr
end
# displaying result
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.display_details()
cust2.display_details()
输出:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
类变量:类变量名称始终以@@符号开头。它可用于不同的对象。类变量属于类,是类的特征。它们需要在使用前进行初始化。考虑类变量的另一种方式是在单个类的上下文中作为全局变量。类变量由该类的所有后代共享。未初始化的类变量将导致错误。
例子:
#!/usr/bin/ruby
# Ruby program to illustrate
# the Class Variables
class Customer
# class variable
@@no_of_customers = 0
def initialize(id, name, addr)
# An instance Variable
@cust_id = id
@cust_name = name
@cust_addr = addr
end
# displaying result
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
# class variable
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.display_details()
cust1.total_no_of_customers()
cust2.display_details()
cust2.total_no_of_customers()
输出:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Total number of customers: 1
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Total number of customers: 2
全局变量:全局变量名总是以$开头。类变量不能跨类使用。如果你想拥有一个跨类可用的变量,你需要定义一个全局变量。它的作用域是全局的,这意味着它可以从程序中的任何地方访问。默认情况下,未初始化的全局变量具有nil值,使用它会导致程序神秘而复杂。
例子:
#!/usr/bin/ruby
# Ruby program to illustrate
# the Global Variables
#!/usr/bin/ruby
# global variable
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
class Class2
def print_global
puts "Global variable in Class2 is #$global_variable"
end
end
class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global
输出:
Global variable in Class1 is 10
Global variable in Class2 is 10