– test1.rb –
class C
def a
end
end
class C
def a
puts “override”
end
end
puts C.new.a # => override
– test2.rb –
class C
def a
end
end
module M
class C
def a
puts “why not override?”
end
end
end
include M
puts C.new.a # => nil
########################
Help Me^^
########################
On Tuesday 29 July 2008, Kyung won Cheon wrote:
end
puts C.new.a # => nil
########################
Help Me^^
########################
C and C::M are two different classes. Modules work as namespaces, so
that you
can have different classes with the same name, provided they’re in
different
modules.
Stefano
On 29.07.2008, at 12:41, Stefano C. wrote:
C and C::M are two different classes
You mean M::C.
just my 2cents, Sandor
Szücs
Kyung won Cheon wrote:
end
puts C.new.a # => nil
########################
Help Me^^
########################
Hhmm, this is actually a little tricky. If I had to hazard a guess I
would say it’s related to the fact that modules included in X are higher
in the lookup chain than X itself. e.g.:
module M
def foo; “M-foo” end
def foo2; “M-foo2” end
end
class A
def foo; “A-foo” end
include M
end
A.new.foo #=> “A-foo”
A.new.foo2 #=> “M-foo2”
so I imagine the same rule applies to constant lookups:
module N
BAR = “N-bar”
BAR2 = “N-bar2”
end
class B
BAR = “B-bar”
include N
end
B::BAR #=> “B-bar”
B::BAR2 #=> “N-bar2”
With warnings enabled, you would have seen that your test1.rb outputs:
(irb):8: warning: method redefined; discarding old a