Writing Module for Ruby

前端 未结 4 941
走了就别回头了
走了就别回头了 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条回答
  •  -上瘾入骨i
    2021-02-01 20:25

    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

提交回复
热议问题