How to call a method from within a module or class

I really love Ruby but there are some concepts that I’m having a hard
time wrapping my head around. Here’s something I thought was simple but
… I’m obviously doing something wrong but what?

Here’s the code I started with:

def make_it_a_double(parameter)
return parameter * 2
end

puts make_it_a_double(2)

It works like a charm but when I try to wrap it inside of a module like
so:

module Outer_module
def make_it_a_double(parameter)
return parameter * 2
end

puts make_it_a_double(2)
end

I get the error:
undefined method `make_it_a_double’ for Outer_module:Module
(NoMethodError)

I’m trying to define methods that will consolidate code within my
modules. What am I doing wrong? I’ve searched but I haven’t found any
examples yet of what I’m doing. (is it that strange?)

Thanks in advance,

M

Jason C. wrote in post #977476:

module Outer_module
def make_it_a_double(parameter)
return parameter * 2
end

puts make_it_a_double(2)
end

I get the error:
undefined method `make_it_a_double’ for Outer_module:Module
(NoMethodError)

What you’ve defined is an instance method (which would be available if
you mixed it into a class). What you want is a method on the module
itself.

Option 1:

module Outer_module
def self.make_it_a_double(parameter)

end
end

Option 2:

module Outer_module
def make_it_a_double(parameter)

end
module_function :make_it_a_double
end

Thanks. That worked. I knew it was something simple.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs