我有以下Ruby腳本,其中Foo類包含模塊Baz,模塊Baz有一個包含的鉤子以使包含類(Foo)的Bar擴展。我只是想知道爲什麼:如何在類上下文中擴展Ruby模塊?
class << klass
extend Bar #this doesn't work. Why?
end
不工作而:
klass.extend(Bar) works.
這裏是我的代碼:
#! /usr/bin/env ruby
module Baz
def inst_method
puts "dude"
end
module Bar
def cls_method
puts "Yo"
end
end
class << self
def included klass
# klass.extend(Bar) this works, but why the other approach below doesn't?
class << klass
extend Bar #this doesn't work. Why?
def hello
puts "hello"
end
end
end
end
end
class Foo
include Baz
end
foo = Foo.new
foo.inst_method
Foo.hello
Foo.cls_method
謝謝你的解釋,我才意識到,在單例類,我需要使用包括而不是擴展吧。 – 2011-05-09 03:11:07