Leon's Blogging

Coding blogging for hackers.

Ruby - Extend vs Include (Mixin)

| Comments

  • extend: 讓 module 內定義的 method 成為 class method
  • include: 讓 module 內定義的 method 成為 instance 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
26
27
28
29
30
31
32
33
34
35
module Animal
  def say
    'hi'
  end
end

class Dog
  include Animal
  def initialize
  end
end

Dog.say
#NoMethodError: undefined method `say' for Dog:Class
Dog.new.say
# => "hi"

class Cat
  extend Animal
end

Cat.say
# => "hi"
Cat.new.say
#NoMethodError: undefined method `say' for #<Cat:0x007fc7e781efa0>

# module 本身也是 class (module.class) 因此可以透過 extend 來延展
module Pig
  extend Animal
end

Pig.say
# => "hi"
Pig.new.say
# NoMethodError: undefined method `new' for Pig:Module

參考文件

Comments