JT's Blog

Do the right things and do the things right.

Ruby Class - Inheritance | Class_method | Instance_method | Class_eval | Instance_eval

| Comments

Ruby 萬物皆物件

Class 可以生成(new) 物件

抽象化的概念很重要

宣告

  • Class name 第一個字必需大寫
  • initialize 只在初始化設定
  • instance variable:以@開頭命名,使用域在instance
  • class variable:以@@開頭命名,等同此class 的全域變數,也就是class 的instance 都可以存取此變數
  • class method 也可以設定pubic, protected, private 等存取權限
1
2
3
4
5
6
7
8
9
class Class_name
   def initialize(input=defalt_value)
     #...
   end

   def methodA
     #...
   end
end

可以使用 .class 查看instance 是哪個class

1
2
p [].class    # Array
p "abc".class # String

存取類別資料

  • attr_reader 幫你產生 getter 方法
  • attr_writer 幫你產生 setter 方法
  • attr_accessor 會幫你在 Ruby 的類別裡產生一對 getter 以及 setter 方法
1
2
3
4
5
class MyClass
  attr_reader  :name   // MyClass#name
  attr_writer  :name   // MyClass#name=
  attr_accessor :name  // 等於以上兩種方法
end
  • 當然也可以自己寫 getter, setter
1
2
3
4
5
6
7
8
9
10
11
class MyClass
  @name

  def name  # getter
    @name
  end

  def name=(name) # setter
    @name = name
  end
end

Class Method

不需要instance 就可以呼叫class.method,同Java 的static

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 方法一
class << MyClass
  def methodA
    puts "Hello"
  end
end

# 方法二
class MyClass
 class << self
   def methodA
     puts "Hello"
   end
 end
end

# 方法三
class MyClass
  def self.methodA
    puts "Hello"
  end
end

繼承

  • 只能單一繼承,也就是一個子類別只能有一個父類別(很重要!)
  • Object 是Ruby 所有class 的父類別,而Object 繼承BasicObject
  • 如果沒有繼承,Ruby 默認所有class 為Object 的子類別
  • 使用is_a?.instance_of? 確認是否為屬於(繼承)此類別
1
2
3
4
5
6
[].is_a?(Array)  # true
"".is_a?(String) # true

p [].instance_of?(Array)  # true
p [].instance_of?(String) # false
p "".instance_of?(String) # true
  • 使用 < 繼承super class
  • 使用super() 呼叫父類別中同名稱的method
1
2
3
4
5
6
class RingAry < Array
  def [](i)
   idx = i % size
   super(idx)
  end
end

CLASS_EVAL、INSTANCE_EVAL

  • instance_eval 定義class method,也可以使用 << 替代
  • class_eval 定義instance method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Foo = Class.new
Foo.class_eval do
  def class_bar
    "class_bar"
  end
end

Foo.instance_eval do
  def instance_bar
    "instance_bar"
  end
end
Foo.class_bar       #=> undefined method ‘class_bar’ for Foo:Class
Foo.new.class_bar   #=> "class_bar"
Foo.instance_bar       #=> "instance_bar"
Foo.new.instance_bar   #=> undefined method ‘instance_bar’ for #<Foo:0x7dce8>

alias、 undef

設定或取消 method 的別名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# alias origin_name new_name
# alias :origin_name :new_name
class C1
  def hello
   "hello"
  end
end

class C2 < C1
  alias super_hello hello
end

p C2.new.super_hello # "hello"

# undef method
# undef :method
class C1
  def methodA
  end
end

class C2 < C1
  undef methodA
  # ...
end

Reference

  • Ruby Programming ver.4

Comments