你應該開始將消息發送到對象的角度來思考。即不要將它們視爲調用方法,請將它們視爲sending message to object(s)
。當你發送消息的時候,對象會檢查它是否可以完成請求(即檢查這個名字中是否存在一個方法,如果存在的話)。所以本質上,sort
是一個消息(方法)到array
對象。
class Array
def sort
# do sorting
end
# example taken from @codycaughlan
# allows you to send message `hi` to your array object
def hi
"Hi, #{length}"
end
end
# so instead of calling method hi([2,9,0])
# send hi message to an array object
[2,9,0].hi
# instead of calling method sort([2,9,0])
# send sort message to an array object
[2,9,0].sort
更新
讓我們說你要編寫一個打印*
乘以你通過數陣列上奏效的方法。
class Array
def print_stars
self.each { |i| puts "*" * i}
end
end
# now let us send a message/call
[1,2,3].print_stars #=> this should produce
*
**
***
正如你可能已經知道的那樣,這些消息可以被鏈接。對於例如
[1,2,3].reverse.print_stars #=> produces
***
**
*
我會如何去與我發送消息的數組對象「玩」。例如,使用這種方法,我對類Array進行「猴子補丁」,我通常會使用參數數組,使用.each遍歷數組,如果元素已經存在,刪除等等。我將如何寫我想要訪問這個數組是我想說的。 – jchi2241
@ user2684075在一個方法中,你使用關鍵字'self'引用接收者。 – toro2k
或者我應該說,有一個與參數相關的變量。在創建與接收器一起工作的方法或我發送消息的對象時,將輸入什麼「變量」? – jchi2241