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

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

by Tom Stuart
November 2017
Beginner to intermediate
344 pages
7h 2m
Chinese
GoTop Information, Inc.
Content preview from 深入理解運算原理|從簡單的機器到無所不能的程式
夠用的 Ruby
|
13
結構
Struct
Ruby 特殊的類別,它的任務是產生其他的類別。透過
Struct
產生的類別,如
果將每個特性名稱傳進
Struct.new
,這種類別將包含 getter setter 方法。習慣上,若
要使用
Struct
產生的類別,要將它當作子類別來用;子類別可以給予名稱,而且它提
供了定義任何額外方法的便利之處。舉例來說,要讓名為
Point
的類別能擁有名為
x
y
的特性,我們可以如下編寫:
class Point < Struct.new(:x, :y)
def +(other_point)
Point.new(x + other_point.x, y + other_point.y)
end
def inspect
"#<Point (#{x}, #{y})>"
end
end
現在我們可以建立
Point
的實體、在 IRB 裡檢閱它們,並且傳送訊息給它們:
>> a = Point.new(2, 3)
=> #<Point (2, 3)>
>> b = Point.new(10, 20)
=> #<Point (10, 20)>
>> a + b
=> #<Point (12, 23)>
不只是我們定義的方法,為了取得和設定它的
x
特性的值,
Point
實體也會回應訊息 x
x=
y
y=
的情況也類似:
>> a.x
=> 2
>> a.x = 35
=> 35
>> a + b
=> #<Point (45, 23)>
Struct.new
產生的類別還有另一項實用的功能,它會像相等方法 ...
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