-1

怎么能Foo返回值@baz。此刻@baz回归nil

module Bar
  @baz = 'baz'

  def get_baz
    @baz
  end
end

class Foo
  extend Bar
end

Foo.get_baz # Currently returns nil

如果这是不可能的,有没有更好的方法来实现这个逻辑?

4

1 回答 1

6

尝试这个:

module Bar
  attr_accessor :baz
  def get_baz
    @baz
  end
end

class Foo
  extend Bar
end

Foo.baz = 'baz'
Foo.get_baz # => 'baz'
Foo.baz # => 'baz'

如果我们看一下Foo的类方法,果然:

Foo.singleton_methods # => [:get_baz, :baz, :baz=]

让我们稍微逛一下(module Bar保持不变):

class Foo
  extend Bar
  include Bar
end

foo = Foo.new
foo.methods.sort # => [:!,..., :baz, :baz=,..., :get_baz,...]
Foo.baz = 'baz'
foo.baz = 'cat'
Foo.baz         # => "baz" 
Foo.baz = 'dog'
foo.baz         # => "cat" 
goo = Foo.new
goo.baz = 'squid'
goo.baz         # => 'squid'

我们可以改为使用为 的特定实例extend引入的方法:BarFoo

class Foo
  extend Bar
end
foo = Foo.new
foo.extend Bar
goo = Foo.new

Foo我们用和得到与上面相同的结果foo,但是

goo.baz = 'rhino' # => # NoMethodError: undefined method 'baz='

不能保持extend直线include?也许这会有所帮助:extend Bar类定义中的此处等效于Foo.singleton_class.send(:include, Bar).

于 2013-10-03T06:05:33.693 回答