I must be making a n00b mistake here. I've written the following Ruby code:
module Foo
def bar(number)
return number.to_s()
end
end
puts Foo.bar(1)
test.rb:6:in <main>': undefined method
bar' for Foo:Module (NoMethodError)
I wish to define a single method on a module called Foo.bar. However, when I try to run the code, I get an undefined method error. What am I doing wrong?
As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.
Private instance/class methods for modulesDefining a private instance method in a module works just like in a class, you use the private keyword. You can define private class methods using the private_class_method method.
You could do with:
module Foo
def self.bar(number)
number.to_s
end
end
puts Foo.bar(1)
Every module in Ruby can be mixed in an object. Once a class is an object, you could mix the methods in a class using the word extend:
module Foo
def bar
'bar'
end
end
class MyInstanceMethods
include Foo
end
class MyClassMethods
extend Foo
end
## Usage:
MyInstanceMethods.new.bar
=> "bar"
MyClassMethods.bar
=> "bar"
If you wish calling the bar method directly from the Foo module, you could do in the same way @xdazz wrote, but since the extend word mixes to a Class:
MyInstanceMethods.class
=> Class
MyClassMethods.class
=> Class
Module.class
=> Class # Hey, module is also a class!!!!!
The trick:
module Foo
extend self # self of Foo is the Module!
def bar
# .....
end
end
Now you can see Foo.bar returning the expected result :P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With