为Ruby编写模块

loc*_*ost 19 ruby

你是如何为ruby编写一个模块的.在python中你可以使用

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

# main.py
import module
module.helloworld("Jim")
Run Code Online (Sandbox Code Playgroud)

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

Rai*_*kis 31

Ruby中的模块与Python中的模块具有不同的用途.通常,您使用模块来定义可以包含在其他类定义中的常用方法.

但Ruby中的模块也可以像Python一样用于在某些命名空间中对方法进行分组.所以你在Ruby中的例子就是(我将模块命名为Module1,因为Module是标准的Ruby常量):

# module1.rb
module Module1
  def self.helloworld(name)
    puts "Hello, #{name}"
  end
end

# main.rb
require "./module1"
Module1.helloworld("Jim")
Run Code Online (Sandbox Code Playgroud)

但是如果你想了解Ruby的基础知识,我建议先从Ruby的快速指南开始- StackOverflow不是学习新编程语言基础知识的最佳方法:)

编辑
从1.9开始,本地路径不再是$ SEARCH_PATH.要从本地文件夹中获取文件,您需要require ./FILErequire_relative FILE


Chi*_*tan 16

人们在这里给出了一些很好的例子,但你也可以用以下方式创建和使用模块(Mixins)

包含的模块

#instance_methods.rb
module MyInstanceMethods
  def foo
    puts 'instance method foo called'
  end
end
Run Code Online (Sandbox Code Playgroud)

扩展的模块

#class_methods.rb
module MyClassMethods
  def bar
    puts 'class method bar called'
  end
end
Run Code Online (Sandbox Code Playgroud)

包含的模块方法就像它们是包含模块的类的实例方法一样

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.
Run Code Online (Sandbox Code Playgroud)

扩展模块方法就像它们是包含模块的类的类方法一样

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
Run Code Online (Sandbox Code Playgroud)

您甚至可以为特定的类对象扩展模块.为此目的而不是在类中扩展模块,你可以做类似的事情

my_obj.extend MyClassMethods
Run Code Online (Sandbox Code Playgroud)

这样,只有my_object会访问MyClassMethods模块方法,而不能访问my_object所属的类的其他实例.模块非常强大.您可以使用核心API文档了解它们

请原谅代码中是否有任何愚蠢的错误,我没试过,但我希望你明白这个想法.


ala*_*dey 0

module NumberStuff 
  def self.random 
    rand(1000000) 
  end 
end 

module LetterStuff 
  def self.random 
    (rand(26) + 65).chr 
  end 
end 

puts NumberStuff.random 
puts LetterStuff.random 
Run Code Online (Sandbox Code Playgroud)
184783
X 
Run Code Online (Sandbox Code Playgroud)

  • 您可能需要使用“def self.random”来避免模块名称更改时出现问题。这是 Ruby 的常见做法。 (6认同)