VKatz VKatz - 2 months ago 7
Ruby Question

Ruby: class inside module take place priority over module?

module TestModule
NAME = "Ruby"
def self.class_method
puts "this is modules method"
end
def instances_method
puts "this is instances methods"
end
class MyClass
puts "this is class inside module"
end
end

puts TestModule::NAME
puts TestModule.class_method
puts TestModule::MyClass

Output:
this is class inside module
Ruby
this is modules method


It Should be :
Ruby
this is modules method
this is class inside module

Is there any priority in ruby between class and module. As ruby is a interpreter so class (class MyClass) should be execute at last.

Answer

It is not about priority, your puts call in class is outside any method. Interpreter reads whole file first, thats why it outputs this is class inside module before any of these calls

puts TestModule::NAME
puts TestModule.class_method
puts TestModule::MyClass

You can test this:

module TestModule
  puts 'reading module'

  class MyClass
    puts 'reading class'
  end
end

and you'll see:

reading module
reading class

And puts TestModule::MyClass this call won't output puts inside your class as you may expect. So just wrap your class puts in instance or class method and call it as TestModule::MyClass.new.instance_method or TestModule::MyClass.class_method correspondingly.

Comments