国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

詳細(xì)解析Ruby中的變量

2019-10-26 19:26:22
字體:
供稿:網(wǎng)友

 變量持有要使用的程序的數(shù)據(jù)的存儲(chǔ)位置。

Ruby支持的有五種類型的變量。在前面的章節(jié)中已經(jīng)經(jīng)歷了一個(gè)簡短描述以及這些變量。本章中介紹的這五種類型的變量。
Ruby的全局變量:

全局變量以$開頭。未初始化的全局變量的值是零,并使用-w選項(xiàng)產(chǎn)生警告。

全局變量的賦值會(huì)改變?nèi)譅顟B(tài)。這是不推薦使用全局變量。他們使得程序的含義模糊。

下面是一個(gè)例子顯示使用全局變量。

#!/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" endendclass1obj = Class1.newclass1obj.print_globalclass2obj = Class2.newclass2obj.print_global

這里$global_variable是一個(gè)全局變量。這將產(chǎn)生以下結(jié)果:

注意: 在Ruby中,把一個(gè)哈希號(hào)(#)字符,在任意變量或常量之前能夠訪問它的值。

Global variable in Class1 is 10
Global variable in Class2 is 10

Ruby的實(shí)例變量:

實(shí)例變量@開始。未初始化的實(shí)例變量的值是零,并產(chǎn)生警告-w選項(xiàng)。

下面是一個(gè)例子顯示使用實(shí)例變量。

#!/usr/bin/rubyclass 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# Create Objectscust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala")# Call Methodscust1.display_details()cust2.display_details()

這里的@cust_id, @cust_name 和 @cust_addr 都是實(shí)例變量。這將產(chǎn)生以下結(jié)果:

Customer id 1Customer name JohnCustomer address Wisdom Apartments, LudhiyaCustomer id 2Customer name PoulCustomer address New Empire road, Khandala

Ruby的類變量:

類變量以@@開始,它們可以被用來在方法定義之前必須初始化。

引用未初始化的類變量產(chǎn)生錯(cuò)誤。類變量之間共享其中的類變量定義的類或模塊的的后代。

覆蓋類變量產(chǎn)生警告-w選項(xiàng)。

下面是一個(gè)例子顯示使用類變量:

#!/usr/bin/rubyclass 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# Create Objectscust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala")# Call Methodscust1.total_no_of_customers()cust2.total_no_of_customers()            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 东丽区| 长海县| 扎鲁特旗| 兴业县| 刚察县| 宁蒗| 闽侯县| 南华县| 尤溪县| 子长县| 尼木县| 盘锦市| 三明市| 侯马市| 梅河口市| 保山市| 峨眉山市| 卓资县| 尤溪县| 丘北县| 德庆县| 密云县| 江山市| 永胜县| 临泽县| 太康县| 嘉义市| 铜陵市| 博白县| 翁牛特旗| 财经| 徐闻县| 鹤壁市| 宜章县| 马龙县| 四子王旗| 连州市| 临汾市| 汝阳县| 大邑县| 贺兰县|