讓我們寫一個簡單的ruby程序。所有Ruby源文件將以擴展名.rb。因此,把下面的源代碼在一個test.rb文件。
#!/usr/bin/ruby -wputs "Hello, Ruby!";
在這里,假定您已經安裝有Ruby解釋器,可以在/usr/bin目錄找到?,F在嘗試運行此程序如下:
$ 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的中的保留字。這些保留字不能用作常數或變量名。然而,它們可以被用作方法名。
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"}
新聞熱點
疑難解答