Writing Module for Ruby

前端 未结 4 933
走了就别回头了
走了就别回头了 2021-02-01 19:47

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


        
4条回答
  •  醉梦人生
    2021-02-01 20:24

    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.

提交回复
热议问题