Tag Archives: ruby

[Ruby notes] Beware of name collisions with mixed-in modules

This is mostly just note to self, since most Ruby developers probably know this.

The following code snippet:

module TestModule
  def change_name
    @name = "TestModule"
  end

  private
  def private_fun
    puts "private_fun"
  end
end

class TestClass
  attr_accessor :name
  include TestModule

  def initialize
    @name = "TestClass"
  end

  def call_private
    private_fun
  end
end

tc = TestClass.new
puts tc.name
tc.change_name
puts tc.name
tc.call_private

Outputs

TestClass
TestModule
private_fun

It shows that when you include a module, everything is brought into the Class namespace, including private functions and instance variables. Coming from the C++ world, I found this somewhat surprising. This shows one of the practical difference between C++ multiple inheritance and Ruby mix-ins: included modules don’t have its own copy of instance variables, and private functions are visible.