我试图使用名为subscriptions
的方法在CurrentPlan内调用CurrentPlan::Subscription我有两个文件这是我的密码current_plan.rb
require_relative 'current_plan/subscription'
class CurrentPlan
# Get all subscriptions through current_plan
def subscriptions
CurrentPlan::Subscription.all
end
end
current_plan = CurrentPlan.new()
current_plan.subscriptions
current_plan/subscription.rb
require_relative '../current_plan'
class CurrentPlan::Subscription
def self.all
%w[subscription_1 subscription_2 subscription_3]
end
end
我收到的错误。
<CurrentPlan:0x0000010191ebd0>
/Users/foobar/Sites/ruby_apps/current_plan.rb:18:in `subscriptions': uninitialized constant CurrentPlan::Subscription (NameError)
from /Users/foobar/Sites/ruby_apps/current_plan.rb:25:in `<top (required)>'
from /Users/foobar/Sites/ruby_apps/current_plan/subscription.rb:3:in `require_relative'
from /Users/foobar/Sites/ruby_apps/current_plan/subscription.rb:3:in `<top (required)>'
from current_plan.rb:14:in `require_relative'
from current_plan.rb:14:in `<main>'
最佳答案
在current_plan/subscription.rb
中,更改为:
require_relative '../current_plan'
class CurrentPlan
class Subscription
def self.all
%w[subscription_1 subscription_2 subscription_3]
end
end
end
当Ruby甚至不知道
CurrentPlan::Subscription
是什么时,它试图解析CurrentPlan
会感到困惑。。。另一种方法是将
require
语句放在文件末尾(在类声明之后),在这种情况下,您不需要修改current_plan.rb
,但这可能会导致其他问题。关于ruby - Ruby:如何使用父类中的方法调用子类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24544623/