国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 安阳市| 同心县| 江安县| 金昌市| 榕江县| 工布江达县| 苏尼特左旗| 临沧市| 安义县| 南木林县| 沙湾县| 锡林浩特市| 鲁山县| 慈利县| 吉隆县| 江口县| 惠水县| 瓦房店市| 阳信县| 吉林省| 靖边县| 泽普县| 寻乌县| 朝阳区| 汉寿县| 会宁县| 奉节县| 大港区| 遂川县| 康定县| 莎车县| 麦盖提县| 苏尼特左旗| 土默特左旗| 江孜县| 小金县| 武安市| 靖安县| 恩施市| 东城区| 伊宁县|