如何在 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 方法。

輸出

它將產生以下輸出。

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

更新於:2022年4月12日

1K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.