Ruby學習筆記 3 容器和迭代器

2021-09-30 07:59:14 字數 1575 閱讀 6226

anarray =    # 用literal的方式

anarray2 = array.new # 使用new的方式

a = [ 1, 3, 5, 7, 9 ] 	» 	[1, 3, 5, 7, 9]

a[1] = 'bat' » [1, "bat", 5, 7, 9]

a[-3] = 'cat' » [1, "bat", "cat", 7, 9]

a[3] = [ 9, 8 ] » [1, "bat", "cat", [9, 8], 9]

a[6] = 99 » [1, "bat", "cat", [9, 8], 9, nil, 99] # 中間缺掉的元素自動用nil補上

class songlist

def (key)

if key.kind_of?(integer) # 這裡的kind_of?函式是obj的乙個函式,當obj是class的物件或者其子類的物件時返回真。

@songs[key]

else

# ...

endend

end

class songlist

def (key)

return @songs[key] if key.kind_of?(integer)

return @songs.find

endend

class array

def inject(n)

each

nend

def sum

inject(0)

enddef product

inject(1)

endend[ 1, 2, 3, 4, 5 ].sum » 15

[ 1, 2, 3, 4, 5 ].product » 120

class file

def file.myopen(*args) # 這裡的*args的意思是將所有的引數都放在乙個array裡面,然後傳遞給args。

afile = file.new(*args) # 這裡的意思是將args的內容又重新變回原來的那種引數樣子。

# if there's a block, pass in the file and close

# the file when it returns

if block_given? # 這個方法是檢查本方法是否被傳遞了乙個code block。

yield afile

afile.close

afile = nil

endreturn afile

endend

class jukeboxbutton < button

def initialize(label, &action) # &action的意思是將這個方法給予的code block轉化成proc物件,並傳遞給action。這個只能出現在最後乙個引數上。

super(label)

@action = action

enddef buttonpressed

@action.call(self)

endend

Ruby學習筆記 13 迭代器

簡單來說 迭代 iterate 指的是重複做相同的事,所以迭代器 iterator 就是用來重複多次相同的事。迭代器是集合支援的方法。儲存一組資料成員的物件稱為集合。在 ruby 中,陣列 array 和雜湊 hash 可以稱之為集合。迭代器返回集合的所有元素,乙個接著乙個。在這裡我們將討論兩種迭代...

ruby 塊 和 迭代器

塊 塊由大量的 組成。您需要給塊取個名稱。塊中的 總是包含在大括號 內。總是從與其具有相同名稱的函式呼叫。這意味著如果您的塊名稱 為 test 那麼您要使用函式 test 來呼叫這個塊。您可以使用 yield 語句來呼叫塊。語法block name 在這裡,您將學到如何使用乙個簡單的 yield 語...

C 筆記 容器 迭代器和演算法

容器是一種資料結構,演算法通過迭代器對容器中資料進行訪問,形成資料結構 演算法的程式結構。容器通過模板可以將型別提煉出來實現泛型,用以儲存不同型別物件的類成為了容器。同一容器儲存同一型別的物件,當容器被銷毀時,容器中的物件也會被銷毀。stl庫提供了一些常用的容器型別,順序容器 vector list...