跳轉到內容

Ruby 程式設計/語法/詞法學

來自華夏公益教科書
(從 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 語言中不是表示式。

華夏公益教科書