Project

General

Profile

Bug #8346

If a module is included, its public instance methods behave like module functions

Added by Alexey Muranov almost 3 years ago. Updated almost 3 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
ruby -v:
2.0.0
Backport:
1.9.3: UNKNOWN, 2.0.0: UNKNOWN
[ruby-core:54690]

Description

=begin
This behavior is unexpected to me:

module M
def f
1
end
end
include M

M.f # => 1

After including the module (({M})), the method (({f})) becomes an instance method of the module for no apparent reason. I would expect an error (instance method not found).
=end

History

#1 [ruby-core:54691] Updated by Alexey Muranov almost 3 years ago

Compare with:

module M
  def self.f
    0
  end
  def f
    1
  end
end
include M

M.f # => 0

#2 [ruby-core:54696] Updated by Jack Nagel almost 3 years ago

alexeymuranov (Alexey Muranov) wrote:

=begin
This behavior is unexpected to me:

module M
def f
1
end
end
include M

Here you have included M in Object, which is why the method is now available on M itself.

Object.method_defined?(:f) => true

#3 [ruby-core:54698] Updated by Marc-Andre Lafortune almost 3 years ago

  • Status changed from Open to Rejected

jacknagel (Jack Nagel) wrote:

Here you have included M in Object, which is why the method is now available on M itself.

Indeed. Another way to understand it: the include has the same effect as doing a def foo at the top level.

You can extend M instead of you want to include M only in the global scope and not in Object.

#4 [ruby-core:54700] Updated by Alexey Muranov almost 3 years ago

Ok, thanks for the explanation.

Also available in: Atom PDF