about class in module

K

Kyung won Cheon

-- 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^^
########################
 
S

Stefano Crocco

-- 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^^
########################

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
 
D

Daniel DeLorme

Kyung said:
-- 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^^
########################

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,191
Latest member
BuyKetoBeez

Latest Threads

Top