Jordan Stewart Jordan Stewart - 7 days ago 5
Ruby Question

NoMethodError when trying to access a "nested method" (or def) in the same module

The piece of code below gives me a

NoMethodError
. I'm a little confused why it gives me an error, and why I can't find anything about nesting methods in modules. Could someone please explain why this isn't working? Can I nest "defs" in modules?

module HowToBasic
module_function

def say_id_and_say_name(id)

# nested method
def say_id(id)
p id
end

# errors here with `say_id_and_say_name':
# undefined method `say_id' for HowToBasic:Module (NoMethodError)
# from teststuff.rb:24:in `<main>'
say_id(id)
end

end

HowToBasic.say_id_and_say_name("99999")


Version:
ruby 2.3.1p112

I had a look and couldn't find anything about this:


Answer

you're missing self keyword in method definition - without it say_id_and_say_name is just an instance method, thus it can't be invoked on Module.

module HowToBasic
  module_function

  def self.say_id_and_say_name(id)
    def self.say_id(id)
      p id
    end

    say_id(id)
  end

end

HowToBasic.say_id_and_say_name("99999")
Comments