Ruby支持以下类型的变量:
实例变量
类变量
局部变量
全局变量
一个实例变量总是开头@。如果您不初始化实例变量,那么它将在编译时从编译器获取nil值。它们的值对于对象的某些实例是有限的或局部的。存在一个实例变量的多个副本,并且同一类的每个对象都可以访问其实例变量的本地副本。他们对实例变量所做的任何更改都不会反映在该变量的其他副本中。实例变量的每个副本都彼此独立。
语法:
@variable_name
示例
class Student def initialize(id, name, addr) @stu_id = id @stu_name = name @stu_addr = addr end def display_details() puts "Student id #@stu_id" puts "Student name #@stu_name" puts "Student address #@stu_addr" end end stu1 = Student.new("1", "Karishma", "Raiwala") stu2 = Student.new("2", "Kayra", "Bhopal") stu1.display_details() stu2.display_details()
输出结果
Student id 1 Student name Karishma Student address Raiwala Student id 2 Student name Kayra Student address Bhopal
一类变量总是与@@声明。如果不初始化类变量,则在编译时会遇到错误。与实例变量类似,它不会使用nil隐式初始化。类变量只有一个副本,并且由同一类的不同对象共享。类变量中任何对象所做的任何更改都将反映在访问它的每个对象中。class变量属于整个类,可在该类内部的任何位置访问。
语法:
@@variable_name
示例
class Student @@no_of_students = 0 def initialize(id, name, addr) @stu_id = id @stu_name = name @stu_addr = addr end def display_details() puts "Student id #@stu_id" puts "Student name #@stu_name" puts "Student address #@stu_addr" end def total_no_of_students() @@no_of_students +=1 puts "Total number of students are #@@no_of_students" end end stu1 = Student.new("1", "Karishma", "Raiwala") stu2 = Student.new("2", "Kayra", "Bhopal") stu1.display_details() stu1.total_no_of_students() stu2.display_details() stu1.total_no_of_students()
输出结果
Student id 1 Student name Karishma Student address Raiwala Total number of students are 1 Student id 2 Student name Kayra Student address Bhopal Total number of students are 2