ruby mixin 错误
我对下面的代码感到困惑。
HTTParty 库具有名为 def self.get(..)
的类方法。
我将其包含在 Client
模块中,然后将该 Client
模块包含在我的 Line
类中并访问 get
方法在我的 def self.hi()
方法中。 但是当我运行时,它会抛出错误:
ruby geek-module.rb
geek-module.rb:12:in `hi': undefined method `get' for Line:Class (NoMethodError)
from geek-module.rb:16:in `<main>'
为什么我无法访问 HTTParty 的 get
方法? 以下是代码:
require 'rubygems'
require 'httparty'
module Client
include HTTParty
end
class Line
include Client
def self.hi
get("http://gogle.com")
end
end
puts Line.hi
I'm confused with the following piece of code.
HTTParty library has class method named def self.get(..)
.
I include it in the Client
module and then include that Client
module in my Line
class and access the get
method in my def self.hi()
method.
But when I run, it throws out the error:
ruby geek-module.rb
geek-module.rb:12:in `hi': undefined method `get' for Line:Class (NoMethodError)
from geek-module.rb:16:in `<main>'
Why I'm not being able to access that get
method of HTTParty?
Following is the code:
require 'rubygems'
require 'httparty'
module Client
include HTTParty
end
class Line
include Client
def self.hi
get("http://gogle.com")
end
end
puts Line.hi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法访问 self.get 方法,因为您使用
include HTTParty
,include 使方法可由类实例而不是类本身访问,您的hi
方法是类方法,但get
方法是实例方法。如果您使用类似的内容:我认为它应该有效
...或者只使用
extend Client
而不是include
You cannot access self.get method because you use
include HTTParty
, include makes methods acessible by instances of class not class himself, yourhi
method is class method butget
method is the instance method. If you use something like:I think it should work
... or just use
extend Client
rather thaninclude
因此,当您在
Client
模块中包含 HTTParty
时,您可以通过Client.get
访问get
方法。当您在Line
类中包含Client
时,您也可以通过Client.get
访问get
方法。实际上,如果您想在 Line 类中使用get
方法,则不需要包含它。所以:或者如果你想在你的 Line 类中使用 get 方法,你可以使用类似的方法:
So, when you
include HTTParty
in theClient
module you can access theget
method throughClient.get
. And when you includeClient
in theLine
class you can access theget
method throughClient.get
too. Actually, if you want to use theget
method in your Line class, you don't need to include it. So:or if you want the
get
method in yourLine
class you can use something like that: