I have a Ruby module for constants. It has a list of variables and one method which applies formatting.
I can't seem to access the method in this module. Any idea why?
A user cannot access instance method directly with the use of the dot operator as he cannot make the instance of the module. To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method.
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.
A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not.
Creating Modules in Ruby To define a module, use the module keyword, give it a name and then finish with an end . The module name follows the same rules as class names. The name is a constant and should start with a capital letter. If the module is two words it should be camel case (e.g MyModule).
If you include
the module the method becomes an instance method but if you extend
the module then it becomes a class method.
module Const def format puts 'Done!' end end class Car include Const end Car.new.format # Done! Car.format # NoMethodError: undefined method format for Car:Class class Bus extend Const end Bus.format # Done! Bus.new.format # NoMethodError: undefined method format
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