Reputation: 3
I ran this script:
module Ma
class CLogic; end
def execute
"Module Ma executes."
end
end
include Ma
CLogic.execute # => "Module Ma executes."
It executes Ma#execute
. I expected something like Undefined method 'execute' for class A.
. I want to understand why. Is class CLogic
extended by the module because of the include
?
Upvotes: 0
Views: 38
Reputation: 114138
Including a module at top-level makes its instance methods available to all objects, not just CLogic
:
include Ma
123.execute #=> "Module Ma executes."
:foo.execute #=> "Module Ma executes."
Array.execute #=> "Module Ma executes."
CLogic.execute #=> "Module Ma executes."
It's basically like:
class Object
include Ma
end
Upvotes: 3
Reputation: 168081
You defined Ma#execute
, which was included in the main environment. That brings the definition into Object
. Since CLogic
is an instance of Object
, CLogic.execute
would be callable.
Upvotes: 2