首發:個人部落格,更新&糾錯&回覆
學不同語言,常將它們的基礎語法搞混,例如if後面有沒有(),後面是then還是:還是。
這種事情毫無技術含量又毫無樂趣可言,但極大地影響流暢度,所以這次再看ruby語法,決定把基礎語法記下來,方便以後檢視。
**放到了這裡,目前只有ruby,待以後用別的語言時再陸續新增。
內容如下,都是最基礎的用法,需要時一看就明白。
#參考:《ruby完全自學手冊》第三章、第四章
#常量大寫字母開頭,變數小寫字母開頭
chang_liang = 1bian_liang = 2bian_liang = "2"
#弱型別
##分支控制#if
if 2 > 1then
#elsif 2>2then
#else
#end
#if後置
puts "
if後置
"if 2 > 1
#unless
unless 2 > 1then
#else
#end
#case
case 1+1when 2then
#when 3then
#else
#end
##迴圈控制
#while
while 1>2
#end#
until
until 1<2
#end#
forfor i in (1..3)
#end#
foreach的另一種寫法
(1..3).each do |i|
#可以用break和next控制,next相當於其他語言的continue
end#
#物件導向
module mymodule#
定義模組
#定義類
class myclass#
類名首字母大寫
attr_accessor :myattr#
定義例項變數
definitialize
@myattr2 = "
@定義的例項變數
"end
public
#訪問控制級別public/protected/private
def mymethod#
定義例項方法
puts "
在例項方法中輸出
" + myattr +@myattr2
endend
#繼承class mysubclass end
#定義模組方法
defmodulemethod
puts
"mymodule的模組方法
"end
end#
模組定義的end#使用
myclass = mymodule::myclass.new#
例項化物件
myclass.myattr = "
例項變數的值"#
為例項變數賦值
myclass.mymethod#
呼叫例項方法
#動態新增方法
defmyclass.newmethod
puts
"動態新增的方法
"end
myclass.newmethod
#載入另乙個檔案中宣告的模組中的類
load '
ruby_another_module.rb
'anotherclass = anothermodule::anotherclass.new#
另乙個檔案中宣告的物件
anotherclass.print
#呼叫其方法#混入
class
usemixin
include mymodule
extend mymodule
endusemixin.new.modulemethod
#include語句的作用,成為類的例項方法
usemixin.modulemethod#
extend語句的作用,成為類的類方法
##**段
def blockmethod#
呼叫**段的方法,其中yield表示執行**段
yield
endblockmethod
#帶引數的**段
def blockmethodwithparam(arg, &b)#
定義顯式使用**段的函式
b.call arg
endblock = proc.new#
定義非匿名**段
blockmethodwithparam("
非匿名**段
", &block)#
使用非匿名**段
blockmethodwithparam("
也可以這樣使用")#
#異常處理
begin
#正常**執行的地方
rescue error#
相當於其他語言的catch
#進行一些調整
retry#
重新嘗試執行
ensure
#相當於其他語言的finally,無論如何都會執行的地方
end#
#基本型別#整數
a=123_456#
可以加下劃線
b=0b101010#
二進位制c=0123#
八進位制d=0xaa#
十六進製制
e=?a#
ascii碼
puts d
#浮點數略
#字串
str = "
hello, world
"str = %#
方便含有引號的內容
str[0] = "我"
puts str
#符號略#區間
(1..3).each#陣列
[1,2,3].each#字典
map =
puts map["鍵甲
"]#正規表示式
"ab12cd
".scan(/\d/)#
正規表示式字面量
puts /\d/.match("
ab12cd
")[0]#
match方法
Ruby的基礎語法入門學習教程
讓我們編寫乙個簡單的 ruby 程式。所有的 ruby 副檔名都是 rb。所以,把下面的源 www.cppcns.com放在 test.rb 檔案中。例項 usr bin ruby w puts hello,ruby 在這裡,假設您的 usr bin 目錄下已經有可用的 ruby 直譯器。現在,嘗試...
Ruby語法了解
三 流程控制 1 條件控制 if 條件表示式 operation1 elsif operation2 else operation3 end unless 條件表示式 operation2 else operation1 end 與if流程相反 2 分支控制 case 表示式 when 值1,值2 ...
Ruby語法小記
0 基本語法 1 輸出 2 輸入 3 基本型別 ruby是沒有型別的,賦值成什麼就是什麼型別。比如 subtotal 100.00,taxrate 0.15,sum 100,name fread 4 全域性變數 在變數前加符號 表示全域性變數。5 類 成員變數 類方法 類例項 object clas...