ader
ader

Reputation: 5

Why does ruby modules gave me NoMethod error?

this is my project tree

main.rb:

$LOAD_PATH<<'./lib'
require 'some_module'
SomeModule::some_func 'p1', 'p2'  

some_module.rb

module SomeModule
  def some_func p1,p2
    puts p1,p2
  end
end

but when i run main.rb.
ruby gave me a NoMethodError, why?

Upvotes: 0

Views: 57

Answers (2)

lacostenycoder
lacostenycoder

Reputation: 11216

You're trying to call the method on the base module which is why you get the error. If you were including this module inside of a class, this method would only be available as an instance method. Since you can't define an instance of the module, you need to define it like this, and you can call it directly on the module.

module SomeModule
  def self.some_func p1,p2
    puts p1,p2
  end
end

However if you wanted to make this an instance method you could do this:

#main.rb
$LOAD_PATH<<'./lib'
require 'some_module'

class Foo
  include SomeModule
end

@foo = Foo.new

@foo.some_func 'p1', 'p2'

#lib/some_module.rb
module SomeModule
  def some_func p1,p2
    puts p1,p2
  end
end

Upvotes: 2

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

You are defining some_func as an instance method of SomeModule:

module SomeModule
  def some_func p1,p2
    puts p1,p2
  end
end

But you are calling it on SomeModule. Since SomeModule is not an instance of SomeModule (it is an instance of Module), you get a NoMethodError:

SomeModule::some_func 'p1', 'p2'  

So, you either need to construct an instance of SomeModule:

(foo = Object.new).extend(SomeModule)
foo.some_func(:p1, :p2)

Or you need to ensure that you define some_func somewhere SomeModule is an instance of, such as SomeModule's singleton class (every object in Ruby is an instance of its singleton class, actually the only instance):

module SomeModule
  def self.some_func(p1, p2)
    puts p1, p2
  end
end

Upvotes: 1

Related Questions