首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为Ruby编写模块

为Ruby编写模块
EN

Stack Overflow用户
提问于 2009-02-14 08:36:53
回答 1查看 21.1K关注 0票数 21

如何为ruby编写一个模块。在python中,您可以使用

# module.py
def helloworld(name):
    print "Hello, %s" % name

# main.py
import module
module.helloworld("Jim")

回到如何在ruby中/为ruby创建模块的问题

EN

回答 1

Stack Overflow用户

发布于 2009-02-14 09:03:28

# 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

在ruby中,模块是用于对方法、常量、类和其他模块进行分组的语法结构的名称。它们是ruby的名称空间的等价物。

另一个概念是按文件分组,如上图所示。然而,这两个概念通常是共存的,一个文件使用单个模块作为其名称空间。

# mod.rb
module Hairy
  def self.shave
    "ouch!"
  end
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/548766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档