模块中的Ruby脚本执行

dec*_*rig 2 ruby

为什么以下失败?

module Test
    def test
        puts "test"
    end

    puts "testing"
    test
end
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

testing
test.rb:6:in `test': wrong number of arguments (ArgumentError)
    from test.rb:6:in `<module:Test>'
    from test.rb:1:in `<main>'
Run Code Online (Sandbox Code Playgroud)

是因为模块还没有"编译",因为还没有达到end关键字?

gle*_*man 6

使用以前未使用的名称可能会消除您的困惑:

module Test
  def my_test
    puts "my_test"
  end
  puts "testing"
  my_test
end
Run Code Online (Sandbox Code Playgroud)

结果是

testing
NameError: undefined local variable or method `my_test' for Test:Module
Run Code Online (Sandbox Code Playgroud)

module...end块中,当你调用时my_test,是什么self(隐式接收器)?这是模块Test.而且没有my_test"模块方法".my_test上面定义的方法类似于实例方法,要发送到包含该模块的某个对象.

您需要定义my_test为"模块方法":

module Test
  def self.my_test
    puts "my_test"
  end
  puts "testing"
  my_test
end
Run Code Online (Sandbox Code Playgroud)

结果是

testing
my_test
Run Code Online (Sandbox Code Playgroud)

如果您想要my_test作为实例方法并且想要在模块定义中调用它:

method Test
  puts "testing"
  Object.new.extend(self).my_test
end
Run Code Online (Sandbox Code Playgroud)

testing
my_test
Run Code Online (Sandbox Code Playgroud)