tags:

views:

19

answers:

1

I am learning ruby and about modules and mixins..

I tried the following code. The name of the ruby file test.rb.

module Mod1
  def Mod1.sayHello()
    puts "Hello Mod1"
  end

end

module Mod2
  def Mod2.sayHello()
    puts "Hello Mod2"
  end
end


class TestMod
  require 'file'
  Mod1.sayHello
end

t = TestMod.new

I am suprised to the output: Hello Mod1 Hello Mod1 (twice)

I am don't have an explanation for this, can somebody help?

+1  A: 

You did not define your initialize method for your class (the constructor). You are simply executing Mod1.sayHello inside the class definition (it is even executed before creating the instance). Try to comment out your t = TestMod.new statement. The output will still stay visible.
Since you include the exact same file, this ends up being executed twice (the file does not get included another time afterwards; ruby prevents this). The class should look like this:

class TestMod
  def initialize
    Mod1.sayHello
  end
end

Why did you include the file anyway? This does not make sense to me.

EDIT: Removed a mistake.

I would recommend to replace the Mod1 and Mod2 inside your module definitions with self. This way you wont have to change the name everywhere if it changes some time.

elusive
That won't work... `def Mod1.sayHello` is the same as saying `def self.sayHello`. In order for the call to Mod1.sayHello to work, the sayHello method must be a class method and not an instance method.
Brian
Also, I believe if no initialize method is defined, ruby acts on the first method it encounters as a constructor when instantiating an object.
Brian
@Brian: Your first statement is true. I made a mistake here and updated my post accordingly. But i do not believe that ruby uses the first method it encounters. `Mod1.sayHello` is a call to the method. This works exactly like the `attr_accessor`-method for example. It is executed at class definition, not instantiation.
elusive
Brian
@all: Thanks for the reply! I am just trying to play around with it, I know this is a crazy thing to do, but i am learning anyways! Thanks!
cgcoder