almost 4 years ago
include 和 extend 的用法
  • include 讓module的method作用在實例變數上
  • extend 讓module的method作用在類別變數上
看以下兩個例子
include
module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end
    
class Bar
  include Foo
end

include module Foo 後,foo只能使用在Bar的實例變數上

Bar.new.foo # heyyyyoooo!

Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class
extend
module Foo
  def foo
   puts 'heyyyyoooo!'
  end
end
    
class Bar
  extend Foo
end

extend module Foo 後,foo只能使用在Bar的類別變數上

Bar.new.foo  # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>

Bar.foo # heyyyyoooo!
← What is super What is yield →
 
comments powered by Disqus