tags:

views:

49

answers:

3
+1  Q: 

Modules in ruby


module Hints
 module Designer
  def message
   "Hello, World!"
  end
 end
end

p Hints::Designer.message


Why this give me the following error...?

undefined method `message' for Hints::Designer:Module (NoMethodError)

+6  A: 

What you need to do is define message as a class method (not as an instance method). Try:

module Hints
 module Designer
  def self.message
   "Hello, World!"
  end
 end
end

puts Hints::Designer.message

If you want to use instance methods with a module, you must extend an object using the module and any given constraints (see http://ruby-doc.org/core/classes/Module.html).

Kevin Sylvestre
this works... great.. thnx aloadz...
Jamal Abdul Nasir
+1  A: 

use p Hints::Designer.new.message

message is an instance method not a class method

clyfe
still got the same error by doing this... :(
Jamal Abdul Nasir
sry, that only works if `Designer` is a Class, I didn't read the whole text carefully, my eyes saw what they were used to see ... http://codepad.org/AZ5TaShz
clyfe
+1  A: 

You want to use this:

module Hints
 module Designer
  def self.message
   "Hello, World!"
  end
 end
end

That is, make message a "class" method (before it was an instance method). This seems a bit weird, but keep in mind that modules are often used to create mixin classes, so an "instance of a module" makes sense in that context.

mipadi