Ruby 全局變量
全局變量以 $ 開頭。未初始化的全局變量的值為 nil,在使用 -w 選項后,會產生警告。
給全局變量賦值會改變全局狀態,所以不建議使用全局變量。
下面的實例顯示了全局變量的用法。
#!/usr/bin/ruby $global_variable = 10class Class1 def print_global puts "Global variable in Class1 is #$global_variable" endendclass Class2 def print_global puts "Global variable in Class2 is #$global_variable" endend class1obj = Class1.newclass1obj.print_globalclass2obj = Class2.newclass2obj.print_global
在這里,$global_variable 是全局變量。這將產生以下結果:
注意:在 Ruby 中,您可以通過在變量或常量前面放置 # 字符,來訪問任何變量或常量的值。
Global variable in Class1 is 10Global variable in Class2 is 10
Ruby 實例變量
實例變量以 @ 開頭。未初始化的實例變量的值為 nil,在使用 -w 選項后,會產生警告。
下面的實例顯示了實例變量的用法。
#!/usr/bin/ruby class Customer def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" endend # 創建對象cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # 調用方法cust1.display_details()cust2.display_details()
在這里,@cust_id、@cust_name 和 @cust_addr 是實例變量。這將產生以下結果:
Customer id 1Customer name JohnCustomer address Wisdom Apartments, LudhiyaCustomer id 2Customer name PoulCustomer address New Empire road, Khandala
Ruby 類變量
類變量以 @@ 開頭,且必須初始化后才能在方法定義中使用。
引用一個未初始化的類變量會產生錯誤。類變量在定義它的類或模塊的子類或子模塊中可共享使用。
在使用 -w 選項后,重載類變量會產生警告。
下面的實例顯示了類變量的用法。
#!/usr/bin/ruby class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" endend # 創建對象cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # 調用方法cust1.total_no_of_customers()cust2.total_no_of_customers()
在這里,@@no_of_customers 是類變量。這將產生以下結果:
新聞熱點
疑難解答