Writing Module for Ruby

前端 未结 4 932
走了就别回头了
走了就别回头了 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:25

    # meth.rb
    def rat
      "rizzo"
    end
    
    # cla.rb
    class Candy
      def melt
        "awwwww...."
      end
    end
    
    # main.rb
    require 'meth'
    require 'cla'
    require 'mod'
    
    puts rat
    puts Candy.new.melt
    puts Hairy.shave
    

    In ruby, modules are the name for syntatic constructs used to group methods, constants, classes, and other modules. They're ruby's equivalent of namespaces.

    A separate concept isgrouping by file, like above. Often, however, the two concepts coexist, with one file using a single module as its namespace.

    # mod.rb
    module Hairy
      def self.shave
        "ouch!"
      end
    end
    

提交回复
热议问题