Ruby 程式設計/語法/字面量
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 | 元-x |
| \M-\C-x | 元控制-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)
還有一種受 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 文件”,其中分隔符本身可以是任何字串
string = <<END on the one ton temple bell a moon-moth, folded into sleep, sits still. END
語法以 << 開頭,緊隨其後是分隔符。要結束字串,分隔符單獨出現在一行上。
有一種更漂亮的方式來編寫 here 文件,它允許結束分隔符透過空格縮排
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 文件是插值的,除非您在分隔符周圍使用單引號。
開頭分隔符後的行的其餘部分不被解釋為字串的一部分,這意味著您可以這樣做
strings = [<<END, "short", "strings"] a long string END => ["a long string\n", "short", "strings"]
您甚至可以“堆疊”多個 here 文件
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 類參考。
這裡 是一個關於其用法的教程。