目錄 (class 篇)
- Scope
- attr_accessor、attr_reader、self
- private、protected
- Inheritance
- ACTIVESUPPORT
- Struct
- Send
- method
1. Scope $: global
、@@: class
、@: instance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Computer $manufacturer = "Mango Computer, Inc." @@files = {hello: "Hello, world!"} def initialize(username, password) @username = username @password = password end def current_user @username end def self.display_files @@files end end
|
1 2 3 4 5
| hal = Computer.new("Dave", 12345) puts "Current user: #{hal.current_user}" puts "Manufacturer: #{$manufacturer}" puts "Files: #{Computer.display_files}"
|
2. attr_accessor (getter & setter)
same as
1 2 3 4 5 6 7
| def baz=(value) @baz = value end def baz @baz end
|
attr_reader、attr_writer、self
1 2 3 4 5 6 7 8
| class Tweet attr_accessor :status attr_reader :created_at def initialize(status) self.status = status @created_at = Time.new end end
|
self
: the current object,需要 setter。
1 2 3 4 5 6 7 8
| class Person attr_reader :name attr_writer :job def initialize(name, job) @name = name @job = job end end
|
- attr_reader + attr_writer = attr_accessor
3. private(cannot be called with explicit receiver)
1 2 3 4 5 6 7 8 9 10 11 12
| class User def up_vote(friend) bump_karma friend.bump_karma end private def bump_karma puts "karma up for #{name}" end end
|
protected (可被 class 內呼叫)
1 2 3 4 5 6 7 8 9 10 11 12
| class User def up_vote(friend) bump_karma friend.bump_karma end protected def bump_karma puts "karma up for #{name}" end end
|
4. Inheritance( Override、super
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Creature def initialize(name) @name = name end def fight return "B" end end class Dragon < Creature def fight puts "A" super end end
|
5. ACTIVESUPPORT
1 2 3 4 5 6
| $ gem install activesupport $ gem install i18n  require 'active_support/all'
|
6. Struct
1 2 3 4 5 6 7 8 9
| class Tweet attr_accessor :user, :status def initialize(user, status) @user, @status = user, status end def to_s "#{user}: #{status}" end end
|
等價於
1 2 3 4 5
| Tweet = Struct.new(:user, :status) do def to_s "#{user}: #{status}" end end
|
7. Send(可以呼叫 private or protected method)
1 2 3 4 5 6 7 8 9 10 11 12
| class Timeline def initialize(tweets) @tweets = tweets end def contents @tweets end private def direct_messages end end
|
1 2 3 4 5 6 7 8 9 10
| tweets = ['Compiling!', 'Bundling...'] timeline = Timeline.new(tweets) timeline.contents 等價於 timeline.send(:contents) 等價於 timeline.send("contents") timeline.send(:direct_messages)
|
8. method (放在記憶體,等等再 .call
)
1 2 3 4 5 6 7 8
| class Timeline def initialize(tweets) @tweets = tweets end def contents @tweets end end
|
1 2 3 4
| content_method = timeline.method(:contents) content_method.call
|