Jimmy
Jimmy

Reputation: 37081

Naming a Ruby method with an existing constant

module Foo
  def self.bar
    "Module.bar"
  end
end

def Foo
  "main.Foo"
end

puts Foo # Foo
puts Foo.bar # Module.bar
puts Foo() # main.Foo
puts Foo.class # Module

Why is it possible for the module Foo and the method Foo to coexist in the same namespace? Why doesn't the definition of the method Foo overwrite the module?

Upvotes: 4

Views: 90

Answers (1)

Chuck
Chuck

Reputation: 237060

They don't exist in the same namespace. Constants and methods are in different namespaces. That's how they coexist. The language looks in the constant namespace unless you use the method-call parens, which unambiguously say "This is supposed to be a method."

Upvotes: 6

Related Questions