简体   繁体   English

访问Ruby模块中的方法

[英]Accessing Methods in Ruby Module

I'm writing my first Ruby module and I have this: 我正在编写我的第一个Ruby模块,我有这个:

/app/module/test_modules/test.rb /app/module/test_modules/test.rb

test.rb looks similar to: test.rb看起来类似于:

module TestModules
  module Test

    def test
      puts 'this is a test'
    end
  end
end

When I call the following from console, I get: 当我从控制台调用以下内容时,我得到:

(main)> TestModule::Test.test
//NoMethodError: private method `test' called for TestModules::Test:Module

How do I make test() visible? 如何使test()可见?

You are calling a class method, whereas you defined test as an instance method. 您正在调用类方法,而您将test定义为实例方法。 You could call it the way you want if you used the module via include or extend . 如果通过includeextend使用模块,可以按照自己的方式调用它。 This article does a good job explaining. 本文做了很好的解释。

module TestModules
  module Test
    def self.test
      puts 'this is a test'
    end
  end
end

Also, 也,

1) 1)

module TestModules
  module Test
    def test
      puts 'this is a test'
    end

    module_function :test
  end
end

2) 2)

module TestModules
  module Test
    extend self
    def test
      puts 'this is a test'
    end
  end
end

The way that you have defined your method, it is a method on an instance of Test - thus it would work if you did: 您定义方法的方式,它是Test实例上的一个方法 - 因此,如果您这样做,它将起作用:

blah = TestModule::Test.new
blah.test

note - and do use it this way, you would need to define Test as a class not a module 注意 - 并且以这种方式使用它,您需要将Test定义为class而不是module

If you want the function to work on the class itself, then you need to define it like so: 如果您希望函数在类本身上工作,那么您需要像这样定义它:

def self.test
    ....
end

And then you can do TestModules::Test.test 然后你可以做TestModules::Test.test

the test method you defined is instance method...try this 您定义的测试方法是实例方法...试试这个

module TestModules
  module Test
    def self.test
      puts 'this is a test'
    end
  end
end

now you can call the method by this TestModules::Test.test 现在您可以通过此TestModules :: Test.test调用该方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM