Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Module Method Access

Tags:

ruby

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?

like image 564
newbie_86 Avatar asked Mar 24 '11 09:03

newbie_86


People also ask

How do you access a module method in Ruby?

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.

How do you call a method in a module in Ruby?

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.

What is module method?

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.

How do I use modules in Ruby?

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).


1 Answers

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 
like image 131
Jonas Elfström Avatar answered Oct 14 '22 02:10

Jonas Elfström