執行個體講解Ruby中的五種變數_ruby專題

來源:互聯網
上載者:User

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 是類變數。這將產生以下結果:

Total number of customers: 1Total number of customers: 2

Ruby 局部變數

局部變數以小寫字母或底線 _ 開頭。局部變數的範圍從 class、module、def 或 do 到相對應的結尾或者從左大括弧到右大括弧 {}。

當調用一個未初始化的局部變數時,它被解釋為調用一個不帶參數的方法。

對未初始化的局部變數賦值也可以當作是變數聲明。變數會一直存在,直到當前域結束為止。局部變數的生命週期在 Ruby 解析程式時確定。

在上面的執行個體中,局部變數是 id、name 和 addr。
Ruby 常量

常量以大寫字母開頭。定義在類或模組內的常量可以從類或模組的內部訪問,定義在類或模組外的常量可以被全域訪問。

常量不能定義在方法內。引用一個未初始化的常量會產生錯誤。對已經初始化的常量賦值會產生警告。

#!/usr/bin/ruby class Example  VAR1 = 100  VAR2 = 200  def show    puts "Value of first Constant is #{VAR1}"    puts "Value of second Constant is #{VAR2}"  endend # 建立對象object=Example.new()object.show

在這裡,VAR1 和 VAR2 是常量。這將產生以下結果:

Value of first Constant is 100Value of second Constant is 200

Ruby 偽變數

它們是特殊的變數,有著局部變數的外觀,但行為卻像常量。您不能給這些變數賦任何值。

    self: 當前方法的接收器對象。
    true: 代表 true 的值。
    false: 代表 false 的值。
    nil: 代表 undefined 的值。
    __FILE__: 當前源檔案的名稱。
    __LINE__: 當前行在源檔案中的編號。

Ruby 基本文字

Ruby 用於文字的規則簡單而又直觀。這部分解釋了 Ruby 中所有的基本文字。
整數

Ruby 支援整數。整數範圍從 -230 到 230-1 或 -262 到 262-1。在這個範圍內的整數是類 Fixnum 的對象,在這個範圍外的整數儲存在類 Bignum 的對象中。

您可以在整數前使用一個可選的前置字元號,一個可選的基礎指標(0 對應 octal,0x 對應 hex,0b 對應 binary),後跟一串數字。底線在數字字串中被忽略。

您可以擷取一個 ASCII 字元或一個用問號標記的逸出序列的整數值。

執行個體:

123         # Fixnum 十進位1_234        # Fixnum 帶有底線的十進位-500         # 負的 Fixnum0377         # 八進位0xff         # 十六進位0b1011        # 二進位?a          # 'a' 的字元編碼?\n         # 分行符號(0x0a)的編碼12345678901234567890 # Bignum

注意:類和對象會在本教程中一個單獨的章節進行講解。
浮點數

Ruby 支援浮點數。它們是帶有小數的數字。浮點數是類 Float 的對象,且可以是下列中任意一個。

執行個體:

123.4        # 浮點值1.0e6        # 科學記號標記法4E20         # 不是必需的4e+20        # 指數前的符號

字串文字

Ruby 字串簡單地說是一個 8 位位元組序列,它們是類 String 的對象。雙引號標記的字串允許替換和使用反斜線符號,單引號標記的字串不允許替換,且只允許使用 \\ 和 \' 兩個反斜線符號。

執行個體:

#!/usr/bin/ruby -w puts 'escape using "\\"';puts 'That\'s right';

這將產生以下結果:

escape using "\"That's right

您可以使用序列 #{ expr } 替換任意 Ruby 運算式的值為一個字串。在這裡,expr 可以是任意的 Ruby 運算式。

#!/usr/bin/ruby -w puts "Multiplication Value : #{24*60*60}";

這將產生以下結果:

Multiplication Value : 86400

反斜線符號

下表列出了 Ruby 支援的反斜線符號:

Ruby 數組

Ruby 數組是在方括弧內放置一系列逗號分隔的對象引用。尾部的逗號會被忽略。
執行個體:

#!/usr/bin/ruby ary = [ "fred", 10, 3.14, "This is a string", "last element", ]ary.each do |i|  puts iend

這將產生以下結果:

fred103.14This is a stringlast element

如需瞭解更多有關 Ruby 數組的細節,請查看 Ruby 數組(Array)。
Ruby 雜湊

Ruby 雜湊是在大括弧內放置一系列鍵/值對,鍵和值之間使用逗號和序列 => 分隔。尾部的逗號會被忽略。
執行個體:

#!/usr/bin/ruby hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }hsh.each do |key, value|  print key, " is ", value, "\n"end

這將產生以下結果:

green is 240red is 3840blue is 15

Ruby 範圍

一個範圍表示一個時間間隔。範圍是通過設定一個開始值和一個結束值來表示。範圍可使用 s..e 和 s...e 來構造,或者通過 Range.new 來構造。

使用 .. 構造的範圍從開始值運行到結束值(包含結束值)。使用 ... 構造的範圍從開始值運行到結束值(不包含結束值)。當作為一個迭代器使用時,範圍會返回序列中的每個值。

範圍 (1..5) 意味著它包含值 1, 2, 3, 4, 5,範圍 (1...5) 意味著它包含值 1, 2, 3, 4 。
執行個體:

#!/usr/bin/ruby (10..15).each do |n|  print n, ' 'end

這將產生以下結果:

10 11 12 13 14 15

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.