原文:http://willh.org/cfc/wiki/index.php/%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B8:%E5%9F%BA%E6%9C%AC%E8%AA%9E%E6%B3%95
新手教學:基本語法
1.保留字
BEGIN???? do????? next??? then
END?????? else??? nil???? true
alias???? elsif?? not???? undef
and?????? end???? or????? unless
begin???? ensure? redo??? until
break???? false?? rescue? when
case????? for???? retry?? while
class???? if????? return? yield
def?????? in????? self??? __FILE__
defined?? module? super?? __LINE__
2.注釋
寫程序時常常會用到注釋,以便日后在觀看程序時可以快速回想該行(段)代碼有何用處
在Ruby,寫注釋可以用一個“?!碧?/p>
#這是注釋
還可以用=begin跟=end來包住要注釋的文字
=begin
這是注釋文字
這是第二行
=end
3.數值
數值的表示方法與其它程序語言沒有太大差異
Ruby支持大數(Bignum),Fixnum,浮點數(Float)
整數
123? #十進制
1_234 #有底線的十進制
O377 #很顯然的,八進制
Oxff #當然是16進制啦
Ob1011 #0跟1組成的二進位
?a #打印出a的Ascii Code
12345678901234567890 #大數
浮點數
123.4 #如你所見,小數
1.0e6 #科學符號
4E20? #沒用到“點(.)"
4e+20 #指數前的符號。
4.字符串
字符串是一組String類別
”abc“ --雙引號字符串允許取代轉義字符。
‘abc’ --單引號字符串不運行取代取代轉義字符。
連接字符串
”foo“ ”bar“? #等同于”foobar“
表示式取代
#$var跟#@var是#{$var}跟#{@var}的縮寫。用#{$變量名稱}或者#{@變量名稱}把變量嵌入
到字符串中。
5.數組
數組的寫法
[] #一個空數組
[1,2,3]#含有三個元素的數組
[1,[2,3]] #含有數組的數組
你可以用以下方法寫數組
%w(foo bar baz) #["foo","bar","baz"]
6.哈希表
一個哈希表是鍵和值的集合
{"id"=>"XY1000","name=>"Ruby","age"=>10}
7.變量
在Ruby中,有五中的變量形態:全局變量(Global variable),Instance variable,類變量(class
variable),局部變量(local variable)與常數。
全局變量:
?開頭加上"$"
???? $foo
Instance Variable
?開頭加上"@"
??@foo
??
類變量
?開頭加上"@@"
??@@foo
??
局部變量
?什么都沒加
??foo
??
常數
?Foo
?
8.常數
常熟要怎樣定義呢?在ruby中不用Const或者const來定義一個常數
在ruby中,只要名稱開頭是”大寫“,就是常數!定義一個常熟為Foo:
Foo
9.流程控制
conditional是條件
if:
?if conditional [then]
??code
?[elsif conditional [then]
??code]
?[else
??code]
?end
?code if conditional
unless:
?unless conditional [then]
??code
?[else
??code]
?end
?code unless conditional
case:
?case expression
??[when expression[, expression...] [then]
??code]...
?[else
??code]
?end
while:
?while conditional [do]
??code
?end
?begin
??code
?end
until:
?until conditional [do]
??code
?end
?begin
??code
?end until conditional
for:
?for variable[, variable...] in expression [do]
??code
?end
Foreach:
?expression.each do |variable[, variable...]| code end
?
?
?
?
?