使模块方法可用而不需要作用域

时间:2015-02-02 14:33:14

标签: ruby

我正在尝试做一些与rspec describe非常相似的事情。

说我在my_mod.rb

中有一个模块
module MyMod
  def say_hello(name)
    puts "hello #{name}"
  end
end

我在另一个文件foo.rb

中使用它
include MyMod # without the include it cannot find say_hello

say_hello "world"

我的问题是 - 我如何让它像rspec一样工作,即require - 模块应该使方法可用,而不必MyMod.say_hello

1 个答案:

答案 0 :(得分:0)

更改原始foo.rb,将include替换为extend。 这样,您就可以使用say_hello "world"

但是,如果您真的想使用require,请定义不带模块的方法:

my_mod.rb

  def say_hello(name)
    puts "hello #{name}"
  end

然后,在foo.rb

require 'my_mod'

say_hello "world"