如何在 Ruby 中使用实例变量
在 Ruby 中,我们可以声明四种不同类型的变量:
局部变量
实例变量
类变量
全局变量
**实例变量** 的名称以 **@ 符号** 开头。需要注意的是,实例变量的内容仅限于其自身引用的对象。
关于 Ruby 中 **实例变量** 的一个重要说明是,即使我们有两个属于同一类的不同对象,我们也可以为它们的实例变量设置不同的值。
Ruby 中实例变量的特性
在检查如何在 Ruby 中使用实例变量之前,让我们了解一些它们的重要特性:
只能通过对象的实例方法访问对象的实例变量。
无需声明 Ruby 实例变量。因此,对象结构是灵活的。
当第一次引用对象时,会动态添加每个实例变量。
如果一个实例对象更改了其实例变量,则不会影响其他实例。
在初始化之前,实例变量的值为 nil。
默认情况下,实例变量是私有的。
示例 1
现在让我们考虑一个非常基本的示例,在其中我们在 Ruby 中声明一个实例变量,然后使用另一个方法来打印该实例变量。
class First_Class # constructor def initialize() # instance variable @Name = "Mukul" end # defining method display def display() puts "Student Name is #@Name" end end # creating an object of First_Class obj = First_Class.new() # calling the instance methods of First_Class obj.display()
在上面的代码中,我们创建了一个名为 **First_Class** 的类,其中包含一个初始化方法(构造函数)和另一个 **display()** 方法,然后我们创建了该类的对象,最后在该类上调用 display 方法。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
它将产生以下输出。
Student Name is Mukul
示例 2
现在,让我们创建另一个方法来创建另一个 **实例** 变量,然后使用另一个方法作为该 **实例** 变量的 setter。请考虑下面显示的代码。
class First_Class # constructor def initialize() # instance variable @Name = "Mukul" end def appendName() @Name += " Latiyan" end # defining method display def display() puts "Student's name is #@Name" end end # creating an object of class Tuts obj = First_Class.new() # calling the appendName method obj.appendName() # calling the display method obj.display()
输出
它将产生以下输出。
Student's name is Mukul Latiyan
广告