欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Ruby中一些基本語法知識點(diǎn)的羅列匯總

 更新時間:2015年05月11日 16:14:32   投稿:goldensun  
這篇文章主要介紹了Ruby中一些基本語法知識點(diǎn)的羅列匯總,包括Ruby中的注釋和標(biāo)識符等基礎(chǔ)內(nèi)容,需要的朋友可以參考下

 讓我們寫一個簡單的ruby程序。所有Ruby源文件將以擴(kuò)展名.rb。因此,把下面的源代碼在一個test.rb文件。

#!/usr/bin/ruby -w

puts "Hello, Ruby!";

在這里,假定您已經(jīng)安裝有Ruby解釋器,可以在/usr/bin目錄找到?,F(xiàn)在嘗試運(yùn)行此程序如下:

$ ruby test.rb

這將產(chǎn)生以下結(jié)果:

Hello, Ruby!

通過以上實(shí)例,我們已經(jīng)看到了一個簡單的Ruby程序,現(xiàn)在讓我們來看看有關(guān)Ruby語法的幾個基本概念:
Ruby程序中的空白符:

在Ruby代碼一般都忽略空白字符,例如空格和制表符,除非當(dāng)它們出現(xiàn)在字符串中。但是,有時它們被使用解釋模棱兩可的報表。詮釋這種類型-w選項啟用時產(chǎn)生警告。

實(shí)例:

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解釋一個語句中以分號和換行符表示結(jié)束。但是,如果Ruby遇到運(yùn)算符,如+,- 或反斜杠結(jié)尾的行,則表示語句繼續(xù)。
Ruby標(biāo)識符:

標(biāo)識符是變量,常量及方法。 Ruby的標(biāo)識符是區(qū)分大小寫的。Ram和RAM在Ruby中是兩個不同意思的標(biāo)識符。

Ruby的標(biāo)識符名稱可以由字母數(shù)字字符和下劃線( _ ).
保留字:

下面的列表顯示了Ruby的中的保留字。這些保留字不能用作常數(shù)或變量名。然而,它們可以被用作方法名。

2015511160750460.jpg (587×347)

 Ruby中heredoc:

"Here Document" 是指建立多行字符串。繼<<可以指定一個字符串或者一個標(biāo)識符來終止字符串字面,當(dāng)前行之后的所有行的終止符字符串的值。

如果終止符是引用,引號的類型決定面向行的字符串常量的類型。注意<<終止符之間不能有空格。

下面是不同的例子:

#!/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é)果:

  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
}

聲明代碼在程序運(yùn)行之前被調(diào)用。
例子:

#!/usr/bin/ruby

puts "This is main Ruby Program"

BEGIN {
  puts "Initializing Ruby Program"
}

這將產(chǎn)生以下結(jié)果:

Initializing Ruby Program
This is main Ruby Program

Ruby END 語句
語法:

END {
  code
}

聲明代碼被稱為程序的結(jié)束。
語法:

#!/usr/bin/ruby

puts "This is main Ruby Program"

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

這將產(chǎn)生以下結(jié)果:

Initializing Ruby Program
This is main Ruby Program
Terminating Ruby Program

Ruby 注釋:

注釋隱藏一行,某一行的一部分或幾行Ruby解釋器忽略解釋程序代碼。可以使用的的哈希字符(#)開頭的一行:

# I am a comment. Just ignore me.

或者,注釋可能是在同一行后一個語句或表達(dá)式:

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


相關(guān)文章

最新評論