Ruby學習筆記2(方法 塊 模組)

2021-07-10 15:27:54 字數 1446 閱讀 8263

ruby中的方法就是其他語言中的函式,名稱應以小寫開頭,以免被解釋為常量。引數可有可無,可以有預設值也可以沒有。每個方法都有預設的返回值,就是最後乙個語句的值。

def

test(a1="ruby", a2="perl")

puts "程式語言為 #"

puts "程式語言為 #"

endtest "c", "c++"

test

要傳入數量可變的引數:

def

sample (*test)

end

alias和undef的用法還不太清楚

塊是一段包含在{}內的**

這段**可以從別處呼叫。甚至像塊來傳遞引數都是可以的,乙個或多個引數。

def

test

yield

5 puts "在 test 方法內"

yield

100end

test 內"}

另一種作為函式引數的呼叫方法:

def

test(&block)

block.call

endtest

在引數前面加上&代表接收乙個塊作為函式的引數。這個引數一般放在最後,特別是同時有*引數出現時。

可以宣告begin和end塊,這將在文件被載入和程式執行完畢後被呼叫。

模組存在的目的主要就是定義乙個命名空間,使這個命名空間裡的方法和常量不會和其他地方有衝突。

模組定義和類定義很像,模組方法和類方法定義也很像,呼叫模組方法就是模組名點上方法名。呼叫模組常量使用模組名雙冒號常量名。

module trig

pi = 3.141592654

def trig.sin(x)

# ..

end def trig.cos(x)

# ..

endend

require語句用於引用已經有的模組。

include用於在類中嵌入模組。

module

a def

a1 end

defa2

endendmodule

b def

b1 end

defb2

endendclass

sample

include

ainclude

bdef

s1 end

endsamp=sample.new

samp.a1

samp.a2

samp.b1

samp.b2

samp.s1

這個例子用一種奇妙的方法實現了sample對a,b的多繼承。

ruby學習筆記 7 方法

定義方法 def method puts method end 呼叫時可以帶或不帶 均可 method method method method 使用引數 def methoduseargs arg1,arg2 print arg1,arg2 end 呼叫時可以帶或不帶 均可 methodusear...

Ruby學習筆 06 方法

ruby 方法與其他程式語言中的函式類似。ruby 方法用於 乙個或多個重複的語句到乙個單元中。方法名應以小寫字母開頭。如果您以大寫字母作為方法名的開頭,ruby 可能會把它當作常量,從而導致不正確地解析呼叫。方法應在呼叫之前定義,否則 ruby 會產生未定義的方法呼叫異常。def method n...

Ruby學習筆記四 模組

一 模組定義及引用,模組就是一段 裡面有一些方法放一起。定義模組用module.end 模組與類非常相似,但是 a 模組不可以有例項物件 b 模組不可以有子類。include math puts sqrt 91 module me def sqrt a puts a a return a a end...