下面小編給大家整理出了一篇關于ruby.html" target="_blank">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的中的保留字。這些保留字不能用作常數或變量名。然而,它們可以被用作方法名。
Ruby中heredoc:
"Here Document" 是指建立多行字符串。繼
如果終止符是引用,引號的類型決定面向行的字符串常量的類型。注意
下面是不同的例子:
#!/usr/bin/ruby -w
This is the first way of creating
here document ie. multiple line string.
EOF
This is the second way of creating
here document ie. multiple line string.
EOF
echo hi there
echo lo there
EOC
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
以上就是Ruby中基本語法的知識學習內容了,更多相關內容請繼續關注武林技術頻道。
新聞熱點
疑難解答
圖片精選