跳到內容

Ruby 程式設計/語法/字面量

來自 Wikibooks,開放的書籍,開放的世界
123                       # Fixnum
-123                      # Fixnum (signed)
1_123                     # Fixnum (underscore is ignored)
-543                      # Negative Fixnum
123_456_789_123_456_789   # Bignum
123.45                    # Float
1.2e-3                    # Float
123.45r                   # Rational, introduced in ruby 2.1
0xaabb                    # (Hexadecimal) Fixnum
0377                      # (Octal) Fixnum
-0b1010                   # (Binary [negated]) Fixnum
0b001_001                 # (Binary) Fixnum
?a                        # ASCII character code for 'a' (97)
?\C-a                     # Control-a (1)
?\M-a                     # Meta-a (225)
?\M-\C-a                  # Meta-Control-a (129)

注意:"?x" 符號的含義已更改。在 ruby 1.9 中,它不再表示 ASCII 數值程式碼,而是一個字串,例如 ?a == "a"

示例

"this is a string"
=> "this is a string"

"three plus three is #{3+3}"
=> "three plus three is 6" 

foobar = "blah"
"the value of foobar is #{foobar}"
=> "the value of foobar is blah" 

'the value of foobar is #{foobar}'
=> "the value of foobar is \#{foobar}"

字串表示式以雙引號或單引號開頭和結尾。雙引號字串表示式會進行反斜槓符號和插值。單引號字串表示式不會進行插值,但會對 \' 和 \\ 進行處理。

反斜槓符號

[編輯 | 編輯原始碼]

也稱為跳脫字元轉義序列,它們用於在字串中插入特殊字元。

示例

"this is a\ntwo line string"
"this string has \"quotes\" in it"
轉義序列 含義
\n 換行符 (0x0a)
\s 空格 (0x20)
\r 回車符 (0x0d)
\t 製表符 (0x09)
\v 垂直製表符 (0x0b)
\f 換頁符 (0x0c)
\b 退格符 (0x08)
\a 響鈴/警報 (0x07)
\e 轉義 (0x1b)
\nnn 八進位制值為 nnn 的字元
\xnn 十六進位制值為 nn 的字元
\unnnn Unicode 程式碼點 U+nnnn(Ruby 1.9 及更高版本)
\u{nnnnn} 超過四個十六進位制數字的 Unicode 程式碼點 U+nnnnn 必須用花括號括起來
\cx 控制-x
\C-x 控制-x
\M-x meta-x
\M-\C-x meta-control-x
\x 字元 x 本身(例如 "" 是雙引號字元)

對於十進位制值的字元,您可以執行以下操作

"" << 197 # 將十進位制值 197 新增到字串中

=> Å

或將它們嵌入,如下所示

"#{197.chr}"

插值允許 Ruby 程式碼出現在字串中。評估該程式碼的結果將插入到字串中

 "1 + 2 = #{1 + 2}"    # => "1 + 2 = 3"
 #{expression}

表示式可以是幾乎任何 Ruby 程式碼。Ruby 在處理字串分隔符方面非常聰明,它通常會按照您的意願進行操作。程式碼將與它在字串外部產生的副作用相同,包括任何錯誤

"the meaning of life is #{1/0}"
=> divided by 0 (ZeroDivisionError)

The % 符號

[編輯 | 編輯原始碼]

還有一種受 Perl 啟發的引用字串方法:使用 %(百分號)並指定一個分隔符,例如

%{78% of statistics are "made up" on the spot}
=> "78% of statistics are \"made up\" on the spot"

任何非字母數字字元都可以用作分隔符,%[包括這些], %?或這些?, %~或甚至這些東西~。透過使用這種符號,通常的字串分隔符 " 和 ' 可以出現在字串中,無需轉義,但當然您選擇的新的分隔符需要轉義。但是,如果您使用 %(括號), %[方括號), %{花括號}%<尖括號> 作為分隔符,則只要它們處於平衡對中,這些相同的分隔符就可以不轉義地出現在字串中

%(string (syntax) is pretty flexible)
=> "string (syntax) is pretty flexible"

修飾符字元可以出現在 % 之後,例如 %q[]、%Q[]、%x[] - 這些決定如何插值字串以及生成什麼型別的物件

修飾符 含義
%q[ ] 非插值字串(除了 \\\[\]
%Q[ ] 插值字串(預設)
%r[ ] 插值正則表示式(標誌可以出現在結束分隔符之後)
%i[ ] 非插值符號陣列,用空格分隔(Ruby 2.0 之後)
%I[ ] 插值符號陣列,用空格分隔(Ruby 2.0 之後)
%w[ ] 非插值單詞陣列,用空格分隔
%W[ ] 插值單詞陣列,用空格分隔
%x[ ] 插值 shell 命令
%s[ ] 非插值符號

以下是一些更多示例

%Q{one\ntwo\n#{ 1 + 2 }}
=> "one\ntwo\n3"

%q{one\ntwo\n#{ 1 + 2 }}
=> "one\\ntwo\\n#{ 1 + 2 }"

%r/#{name}/i
=> /nemo/i

%w{one two three}
=> ["one", "two", "three"]

%i{one two three} # after Ruby 2.0
=> [:one, :two, :three]

%x{ruby --copyright}
=> "ruby - Copyright (C) 1993-2009 Yukihiro Matsumoto\n"

"Here document" 符號

[編輯 | 編輯原始碼]

還有一種建立字串的方法,稱為“here document”,其中分隔符本身可以是任何字串

string = <<END
on the one ton temple bell
a moon-moth, folded into sleep,
sits still.
END

語法以 << 開頭,後面緊跟著分隔符。要結束字串,分隔符單獨出現在一行上。

有一種更簡潔的寫法,可以使結束分隔符縮排空白

string = <<-FIN
           on the one-ton temple bell
           a moon-moth, folded into sleep
           sits still.

           --Taniguchi Buson, 18th century; translated by X. J. Kennedy
         FIN

要使用分隔符中的非字母數字字元,可以對它進行引用

string = <<-"."
           Orchid - breathing
           incense into
           butterfly's wings.

           --Matsuo Basho; translated by Lucien Stryk
         .

Here document 是插值的,除非您在分隔符周圍使用單引號

開頭分隔符後的行其餘部分不被解釋為字串的一部分,這意味著您可以執行以下操作

strings = [<<END, "short", "strings"]
a long string
END

=> ["a long string\n", "short", "strings"]

您甚至可以“堆疊”多個 here document

string = [<<ONE, <<TWO, <<THREE]
  the first thing
ONE
  the second thing
TWO
  and the third thing
THREE
=> ["the first thing\n", "the second thing\n", "and the third thing\n"]

您甚至可以應用方法

s = <<END.chomp.upcase # Stripped of ending new-line and uppercased.
abc
END
=> "ABC"

命令擴充套件

[編輯 | 編輯原始碼]

您可以使用反引號引起來的字串執行 shell 命令並執行任何外部程式,並獲取輸出。

# Print contents of current directory, just like in console window.
puts `dir`
# Resolve a domain name to its IP address.
domain = 'ruby-lang.org'
ip = `nslookup #{domain}`.match(/\d+\.\d+\.\d+\.\d+/).to_s # => 151.101.85.178
# Download this web-page with "curl", displaying the progress, then find and print an example from it.
puts `curl https://wikibook.tw/w/index.php?title=Ruby_Programming/Syntax/Literals`.encode('utf-8')
  .match(%r(<h2(?:.(?!</h2>))*Numerics.*?(?=<h2))imsu).to_s    # Reducing to one section.
  .match(%r((?<=<pre>).*?(?=</pre>))imsu ).to_s                # Reducing to an example in it.

正則表示式

[編輯 | 編輯原始碼]
regex_one = /chapter_\d+/i #=> /chapter_\d+/i
regex_two = %r(/chapter_\d+)i #=> /\/chapter_\d+/i

陣列是由非負整數索引的多個物件的集合。您可以透過編寫 Array.new、編寫方括號內可選的用逗號分隔的值列表,或者如果陣列只包含字串物件,則編寫以 %w 開頭的用空格分隔的字串來建立陣列物件。

array_one   = Array.new
array_two   = []                # shorthand for Array.new
array_three = ["a", "b", "c"]   # array_three contains "a", "b" and "c"
array_four  = %w[a b c d e f g] # array_four also contains "a", "b" and "c"
array_three[0]                # => "a"
array_three[2]                # => "c"
array_four[0]                 # => "a"
#negative indices are counted back from the end
array_four[-2]                # => "f"
#[start, count] indexing returns an array of count objects beginning at index start
array_four[1,3]               # => ["b", "c", "d"]
#using ranges. The end position is included with two periods but not with three
array_four[0..4]              # => ["a", "b", "c", "d", "e"]
array_four[0...4]             # => ["a", "b", "c", "d"]

最後一種方法,使用 %w,本質上是當子字串僅用空格分隔時,String 方法 split 的簡寫。在以下示例中,前兩種建立字串陣列的方法在功能上是相同的,而最後兩種方法建立了截然不同的(但都有效的)陣列。

 array_one   = %w'apple orange pear'            # => ["apple", "orange", "pear"]
 array_two   = 'apple orange pear'.split        # => ["apple", "orange", "pear"]
 array_one   == array_two                       # => true
 array_three = %w'dog:cat:bird'                 # => ["dog:cat:bird"]
 array_four  = 'dog:cat:bird'.split(':')        # => ["dog", "cat", "bird"]
 array_three == array_four                      # => false

雜湊基本上與陣列相同,只是雜湊不僅包含值,還包含指向這些值的鍵。每個鍵在雜湊中只能出現一次。雜湊物件透過編寫 Hash.new 或編寫花括號內可選的用逗號分隔的 key => value 對列表來建立。

hash_one   = Hash.new
hash_two   = {}                             # shorthand for Hash.new
hash_three = {"a" => 1, "b" => 2, "c" => 3} #=> {"a"=>1, "b"=>2, "c"=>3}

通常,符號 用於雜湊鍵(允許更快地訪問),因此您會看到雜湊宣告如下

hash_sym   = { :a => 1, :b => 2, :c => 3}   #=> {:b=>2, :c=>3, :a=>1}
hash_sym   = { a: 1, b: 2, c: 3}            #=> {:b=>2, :c=>3, :a=>1}

後一種形式是在 Ruby 1.9 中引入的。

雜湊排序

[編輯 | 編輯原始碼]

請注意,在 1.8 中,遍歷雜湊將按照“隨機”順序遍歷鍵值對。從 1.9 開始,它將按照插入順序遍歷它們。但是請注意,如果您在不先刪除的情況下重新插入鍵,或者更改了現有鍵的值,則鍵在迭代中的順序不會改變。

>> a = {:a => 1, :b => 2, :c => 3}
=> {:a=>1, :b=>2, :c=>3}
>> a.keys # iterate over, show me the keys
=> [:a, :b, :c]
>> a[:b] = 2
> a.keys
=> [:a, :b, :c] # same order
>> a.delete(:b)
>> a[:b] = 4 # re insert now
=> 4
>> a.keys
=> [:a, :c, :b] # different order

範圍表示型別所有可能值的子集,更準確地說,是起始值和結束值之間所有可能的值。

這可能是

  • 0 到 5 之間的所有整數。
  • 0 到 1 之間的所有數字(包括非整數),但不包括 1。
  • 't' 到 'y' 之間的所有字元。

在 Ruby 中,這些範圍由以下表示

0..5
0.0...1.0
't'..'y'

因此,範圍由起始值、結束值以及是否包含結束值(在此簡短語法中,使用兩個點表示包含,三個點表示不包含)組成。

範圍表示一組值,而不是一個序列。因此,

5..0

雖然語法正確,但會產生長度為零的範圍。

範圍只能從同一個類的例項或公共父類的子類中形成,該父類必須是 Comparable(實現 <=>)。

範圍是 Range 類的例項,具有一些方法,例如,確定某個值是否在範圍內

r = 0..5
puts r === 4  # => true
puts r === 7  # => false

有關所有 Range 方法的詳細資訊,請參閱 Range 類參考

這裡 是關於它們用法的教程。

華夏公益教科書