1. 程式人生 > >當 Class attribute 遇見 inheritance

當 Class attribute 遇見 inheritance

Ruby的類變數遇到繼承的時候:

  class F
@@a = 'f'
def foo
puts @@a
end
end

class A < F
@@a = 'a'
end

class B < F
@@a = 'b'
end


a = A.new
a.foo # => 'b'


Rails是這麼解決的:[url]http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb?rev=7220[/url]