我试图使用名为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/

10-13 02:08