讓我們寫一個(gè)簡(jiǎn)單的ruby程序。所有Ruby源文件將以擴(kuò)展名.rb。因此,把下面的源代碼在一個(gè)test.rb文件。
1 2 3 | #!/usr/bin/ruby -w puts "Hello, Ruby!" ; |
在這里,假定您已經(jīng)安裝有Ruby解釋器,可以在/usr/bin目錄找到。現(xiàn)在嘗試運(yùn)行此程序如下:
1 | $ ruby test .rb |
這將產(chǎn)生以下結(jié)果:
1 | Hello, Ruby! |
通過以上實(shí)例,我們已經(jīng)看到了一個(gè)簡(jiǎn)單的Ruby程序,現(xiàn)在讓我們來看看有關(guān)Ruby語法的幾個(gè)基本概念:
Ruby程序中的空白符:
在Ruby代碼一般都忽略空白字符,例如空格和制表符,除非當(dāng)它們出現(xiàn)在字符串中。但是,有時(shí)它們被使用解釋模棱兩可的報(bào)表。詮釋這種類型-w選項(xiàng)啟用時(shí)產(chǎn)生警告。
實(shí)例:
1 2 | 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程序行結(jié)尾:
Ruby解釋一個(gè)語句中以分號(hào)和換行符表示結(jié)束。但是,如果Ruby遇到運(yùn)算符,如+,- 或反斜杠結(jié)尾的行,則表示語句繼續(xù)。
Ruby標(biāo)識(shí)符:
標(biāo)識(shí)符是變量,常量及方法。 Ruby的標(biāo)識(shí)符是區(qū)分大小寫的。Ram和RAM在Ruby中是兩個(gè)不同意思的標(biāo)識(shí)符。
Ruby的標(biāo)識(shí)符名稱可以由字母數(shù)字字符和下劃線( _ ).
保留字:
下面的列表顯示了Ruby的中的保留字。這些保留字不能用作常數(shù)或變量名。然而,它們可以被用作方法名。
Ruby中heredoc:
"Here Document" 是指建立多行字符串。繼<<可以指定一個(gè)字符串或者一個(gè)標(biāo)識(shí)符來終止字符串字面,當(dāng)前行之后的所有行的終止符字符串的值。
如果終止符是引用,引號(hào)的類型決定面向行的字符串常量的類型。注意<<終止符之間不能有空格。
下面是不同的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/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 |
這將產(chǎn)生以下結(jié)果:
1 2 3 4 5 6 7 8 | 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 語句
語法:
1 2 3 | BEGIN { code } |
聲明代碼在程序運(yùn)行之前被調(diào)用。
例子:
1 2 3 4 5 6 7 | #!/usr/bin/ruby puts "This is main Ruby Program" BEGIN { puts "Initializing Ruby Program" } |
這將產(chǎn)生以下結(jié)果:
1 2 | Initializing Ruby Program This is main Ruby Program |
Ruby END 語句
語法:
1 2 3 | END { code } |
聲明代碼被稱為程序的結(jié)束。
語法:
1 2 3 4 5 6 7 8 9 10 | #!/usr/bin/ruby puts "This is main Ruby Program" END { puts "Terminating Ruby Program" } BEGIN { puts "Initializing Ruby Program" } |
這將產(chǎn)生以下結(jié)果:
1 2 3 | Initializing Ruby Program This is main Ruby Program Terminating Ruby Program |
Ruby 注釋:
注釋隱藏一行,某一行的一部分或幾行Ruby解釋器忽略解釋程序代碼。可以使用的的哈希字符(#)開頭的一行:
# I am a comment. Just ignore me.
或者,注釋可能是在同一行后一個(gè)語句或表達(dá)式:
name = "Madisetti" # This is again comment
可以注釋掉多行如下:
1 2 3 4 | # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. |
這里是另一種形式。此塊注釋隱藏幾行注釋: =begin/=end:
1 2 3 4 5 6 | = begin This is a comment. This is a comment, too. This is a comment, too. I said that already. = end |