How do you write a module for ruby. in python you can use
# module.py
def helloworld(name):
print "Hello, %s" % name
# main.py
import module
module.helloworld("Jim")
Back to the Question how do you create a module in/for ruby
Modules in Ruby have different purpose than modules in Python. Typically you use modules to define common methods that could be included in other class definition.
But modules in Ruby could also be used in similar way as in Python just to group methods in some namespace. So your example in Ruby would be (I name module as Module1 as Module is standard Ruby constant):
# module1.rb
module Module1
def self.helloworld(name)
puts "Hello, #{name}"
end
end
# main.rb
require "./module1"
Module1.helloworld("Jim")
But if you want to understand the basics of Ruby I would recommend to start with some quick guide to Ruby - StackOverflow is not the best way how to learn basics of new programming language :)
EDIT
Since 1.9 the local path isn't in $SEARCH_PATH anymore. To requrie a file from your local folder you either need require ./FILE
or require_relative FILE
People have given some nice examples here but you can create and use modules in the following manner as well (Mixins)
Module to be included
#instance_methods.rb
module MyInstanceMethods
def foo
puts 'instance method foo called'
end
end
Module to be extended
#class_methods.rb
module MyClassMethods
def bar
puts 'class method bar called'
end
end
Included module methods act as if they are instance methods of the class in which the module is included
require 'instance_methods.rb'
class MyClass
include MyInstanceMethods
end
my_obj = MyClass.new
my_obj.foo #prints instance method foo called
MyClass.foo #Results into error as method is an instance method, _not_ a class method.
Extended module methods act as if they are class methods of the class in which the module is included
require 'class_methods.rb'
class MyClass
extend MyClassMethods
end
my_obj = MyClass.new
my_obj.bar #Results into error as method is a class method, _not_ an instance method.
MyClass.bar #prints class method bar called
You can even extend a module just for a specific object of class. For that purpose instead of extending the module inside the class, you do something like
my_obj.extend MyClassMethods
This way, only the my_object
will have access to MyClassMethods
module methods and not other instances of the class to which my_object belongs. Modules are very very powerful. You can learn ore about them using core API documentation
Please excuse if there are any silly mistakes in the code, I did not try it but I hope you get the idea.
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