Skip to Content
深入理解運算原理|從簡單的機器到無所不能的程式
book

深入理解運算原理|從簡單的機器到無所不能的程式

by Tom Stuart
November 2017
Beginner to intermediate
344 pages
7h 2m
Chinese
GoTop Information, Inc.
Content preview from 深入理解運算原理|從簡單的機器到無所不能的程式
6
|
1
我們在這裡建了新的物件,作法是將
new
訊息傳給名為
Object
的物件,這是個內建的特
殊物件。只要建立了新物件,接著就替它定義
#add
方法。這個
#add
方法會將它的兩個
引數相加,並傳回結果,但這並不需要明確的 return,因為方法裡所執行的最後一個運
算式的值,會自動傳回。當我們將
add
訊息和引數
2
3
傳給該物件,就會執行物件的
#add
方法,接著我們就能得到想要的答案了。
要將訊息傳給物件方式,通常先寫出接收端的物件,然後寫一個點,再寫訊息名稱(例
o.add
),但是 Ruby 會持續追蹤
目前物件
current object
稱為
self
,並且允許我
們在此物件之後寫上點和訊息名稱,即可將訊息傳送給該物件(也就是不必明確寫出接
收端的物件)。舉例來說,在方法定義的內部,目前物件一定就是收到訊息的物件(所
收到的訊息會讓方法因而執行),所以在某個物件的方法內部,我們可以傳送其他的訊
息給同一個物件,而不需要特別指明是哪個物件:
>> de f o.add_twice(x, y)
add(x, y) + add(x, y)
end
=> nil
>> o.add_twice(2, 3)
=> 10
請注意,雖然原本應該寫成
o.add(x, y)
,但只要改寫成
add(x, y)
,就可以從
#add_
twice
方法的內部傳送
add
訊息到
o
,因為
add_twice
訊息原本就是要送往
o
在任何方法定義之外的目前物件,是個名為
main
的頂層特別物件,沒有指定接收者的
任何訊息,都會送給它;同樣的,任何沒有指定物件的方法定義 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JSON實務手冊

JSON實務手冊

Tom Marrs

Publisher Resources

ISBN: 9789864766000