Ruby 程式設計/語法/詞法
外觀
識別符號是用來標識變數、方法或類的名稱。
與大多數語言一樣,有效的識別符號由字母數字字元(A-Za-z0-9)和下劃線(_)組成,但不能以數字開頭(0-9)。此外,作為方法名稱的識別符號可以以問號(?)、感嘆號(!)或等號(=).
)結尾。識別符號的長度沒有任意限制(即它可以根據需要長,只受計算機記憶體的限制)。最後,有一些保留字不能用作識別符號。
示例
foobar ruby_is_simple
行註釋從一個裸的 '#' 字元開始,一直到行尾。程式碼註釋和文件最好使用 Ruby 嵌入式文件實現。 http://www.ruby-doc.org/docs/ProgrammingRuby/html/rdtool.html
示例
# this line does nothing; print "Hello" # this line prints "Hello"
示例
=begin Everything between a line beginning with `=begin' down to one beginning with `=end' will be skipped by the interpreter. These reserved words must begin in column 1. =end
以下單詞在 Ruby 中是保留字
__FILE__ and def end in or self unless __LINE__ begin defined? ensure module redo super until BEGIN break do false next rescue then when END case else for nil retry true while alias class elsif if not return undef yield
你可以在這裡找到一些使用它們的示例 這裡。
示例
true (1 + 2) * 3 foo() if test then okay else not_good end
所有變數、字面量、控制結構等等都是表示式。將它們組合在一起就形成了一個程式。可以用換行符或分號(;)來分隔表示式——但是,帶反斜槓(\)的換行符將繼續到下一行。
由於在 Ruby 中,控制結構也是表示式,因此可以執行以下操作
foo = case 1
when 1
true
else
false
end
在 C 等語言中,上面的等效程式碼會生成語法錯誤,因為在 C 語言中,控制結構不是表示式。