Reputation: 3395
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:
Upvotes: 1
Views: 294
Reputation: 4533
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(id)
p id
end
def self.say_id_and_say_name(id)
say_id(id)
end
end
HowToBasic.say_id_and_say_name("99999")
Upvotes: 4