Dasmowenator
Dasmowenator

Reputation: 5438

Why can't Ruby find a method declared right above?

I have a simple file called helper.rb that looks like this:

module MyHelper
  def initialize_helper
    puts "Initialized"
  end

  initialize_helper()
end

And another simple file like this:

require_relative 'helper.rb'
include MyHelper
puts "Done"

But when I run this second file, it results in this error:

helper.rb:6:in `<module:MyHelper>': undefined method `initialize_helper' for MyHelper:Module (NoMethodError)

Why can't Ruby find this initializeHelper method defined directly above where I'm calling it???

Upvotes: 0

Views: 46

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70297

Try

def self.initialize_helper
  puts "Initialized"
end

Without the self., you're declaring an instance method intended to be called on objects, not the module itself. So, for instance, your original code is intended to be used like

module MyHelper
  def initialize_helper
    puts "Initialized"
  end
end
class Foo
  include MyHelper
end
Foo.new.initialize_helper

But if you want to call it on the module, you need to have self. in front of it to make it a method on the module itself.

Upvotes: 3

Related Questions