讓我們寫一個簡單的ruby程序。所有Ruby源文件將以擴展名.rb。因此,把下面的源代碼在一個test.rb文件。
#!/usr/bin/ruby -wputs "Hello, Ruby!";
在這里,假定您已經安裝有Ruby解釋器,可以在/usr/bin目錄找到。現(xiàn)在嘗試運行此程序如下:
$ ruby test.rb
這將產生以下結果:
Hello, Ruby!
通過以上實例,我們已經看到了一個簡單的Ruby程序,現(xiàn)在讓我們來看看有關Ruby語法的幾個基本概念:
Ruby程序中的空白符:
在Ruby代碼一般都忽略空白字符,例如空格和制表符,除非當它們出現(xiàn)在字符串中。但是,有時它們被使用解釋模棱兩可的報表。詮釋這種類型-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遇到運算符,如+,- 或反斜杠結尾的行,則表示語句繼續(xù)。
Ruby標識符:
標識符是變量,常量及方法。 Ruby的標識符是區(qū)分大小寫的。Ram和RAM在Ruby中是兩個不同意思的標識符。
Ruby的標識符名稱可以由字母數(shù)字字符和下劃線( _ ).
保留字:
下面的列表顯示了Ruby的中的保留字。這些保留字不能用作常數(shù)或變量名。然而,它們可以被用作方法名。
Ruby中heredoc:
"Here Document" 是指建立多行字符串。繼<<可以指定一個字符串或者一個標識符來終止字符串字面,當前行之后的所有行的終止符字符串的值。
如果終止符是引用,引號的類型決定面向行的字符串常量的類型。注意<<終止符之間不能有空格。
下面是不同的例子:
#!/usr/bin/ruby -wprint <<EOF This is the first way of creating here document ie. multiple line string.EOFprint <<"EOF"; # same as above This is the second way of creating here document ie. multiple line string.EOFprint <<`EOC` # execute commands echo hi there echo lo thereEOCprint <<"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 therelo there I said foo. I said bar.
Ruby BEGIN 語句
語法:
BEGIN { code}
聲明代碼在程序運行之前被調用。
例子:
#!/usr/bin/rubyputs "This is main Ruby Program"BEGIN { puts "Initializing Ruby Program"}
這將產生以下結果:
Initializing Ruby ProgramThis is main Ruby Program
Ruby END 語句
語法:
END { code}
聲明代碼被稱為程序的結束。
語法:
#!/usr/bin/rubyputs "This is main Ruby Program"END { puts "Terminating Ruby Program"}BEGIN { puts "Initializing Ruby Program"}
這將產生以下結果:
Initializing Ruby ProgramThis is main Ruby ProgramTerminating Ruby Program
Ruby 注釋:
注釋隱藏一行,某一行的一部分或幾行Ruby解釋器忽略解釋程序代碼??梢允褂玫牡墓W址ǎ#╅_頭的一行:
# 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:
=beginThis is a comment.This is a comment, too.This is a comment, too.I said that already.=end
新聞熱點
疑難解答
圖片精選