Ruby - 語法



讓我們用 Ruby 寫一個簡單的程式。所有 Ruby 檔案都將副檔名為 .rb。因此,將以下原始碼放入 test.rb 檔案中。

#!/usr/bin/ruby -w

puts "Hello, Ruby!";

這裡,我們假設您的 Ruby 直譯器位於 /usr/bin 目錄中。現在,嘗試按如下方式執行此程式:

$ ruby test.rb

這將產生以下結果:

Hello, Ruby!

您已經看到了一個簡單的 Ruby 程式,現在讓我們瞭解一些與 Ruby 語法相關的基本概念。

Ruby 程式中的空格

空格字元(例如空格和製表符)通常在 Ruby 程式碼中被忽略,除非它們出現在字串中。但是,有時它們用於解釋含糊不清的語句。當啟用 -w 選項時,此類解釋會產生警告。

示例

a + b is interpreted as a+b ( Here a is a local variable)
a  +b is interpreted as a(+b) ( Here a is a method call)

Ruby 程式中的行尾

Ruby 將分號和換行符解釋為語句的結束。但是,如果 Ruby 在行尾遇到運算子,例如 +、- 或反斜槓,則表示語句的延續。

Ruby 識別符號

識別符號是變數、常量和方法的名稱。Ruby 識別符號區分大小寫。這意味著 Ram 和 RAM 在 Ruby 中是兩個不同的識別符號。

Ruby 識別符號名稱可以由字母數字字元和下劃線字元 (_) 組成。

保留字

以下列表顯示了 Ruby 中的保留字。這些保留字不能用作常量或變數名。但是,它們可以用作方法名。

BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return while
def in self __FILE__
defined? module super __LINE__

Ruby 中的文件塊

“文件塊”是指從多行構建字串。在 << 後面,您可以指定一個字串或識別符號來終止字串文字,並且從當前行到終止符的所有行都是字串的值。

如果終止符被引用,引號的型別決定了面向行的字串文字的型別。請注意,<< 和終止符之間不能有空格。

以下是不同的示例:

#!/usr/bin/ruby -w

print <<EOF
   This is the first way of creating
   here document ie. multiple line string.
EOF

print <<"EOF";                # same as above
   This is the second way of creating
   here document ie. multiple line string.
EOF

print <<`EOC`                 # execute commands
	echo hi there
	echo lo there
EOC

print <<"foo", <<"bar"  # you can stack them
	I said foo.
foo
	I said bar.
bar

這將產生以下結果:

   This is the first way of creating
   her document ie. multiple line string.
   This is the second way of creating
   her document ie. multiple line string.
hi there
lo there
      I said foo.
      I said bar.

Ruby BEGIN 語句

語法

BEGIN {
   code
}

宣告在程式執行之前呼叫的程式碼

示例

#!/usr/bin/ruby

puts "This is main Ruby Program"

BEGIN {
   puts "Initializing Ruby Program"
}

這將產生以下結果:

Initializing Ruby Program
This is main Ruby Program

Ruby END 語句

語法

END {
   code
}

宣告在程式結束時呼叫的程式碼

示例

#!/usr/bin/ruby

puts "This is main Ruby Program"

END {
   puts "Terminating Ruby Program"
}
BEGIN {
   puts "Initializing Ruby Program"
}

這將產生以下結果:

Initializing Ruby Program
This is main Ruby Program
Terminating Ruby Program

Ruby 註釋

註釋將一行、部分行或幾行隱藏在 Ruby 直譯器之外。您可以在一行的開頭使用井號 (#):

# I am a comment. Just ignore me.

或者,註釋可以在語句或表示式之後出現在同一行:

name = "Madisetti" # This is again comment

您可以如下注釋多行:

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

這是另一種形式。此塊註釋使用 =begin/=end 隱藏直譯器中的幾行:

=begin
This is a comment.
This is a comment, too.
This is a comment, too.
I said that already.
=end
廣告
© . All rights reserved.