Ruby 为什么我的第二个类不允许我从第一个类调用我的方法?

Ruby 为什么我的第二个类不允许我从第一个类调用我的方法?,ruby,class,inheritance,methods,Ruby,Class,Inheritance,Methods,我正在为一个小游戏创建一个代码,该游戏由4匹马在终端上跑一段设定的距离组成。我把它放在输出我添加的马和我的用户马的地方,但是当我去下一个类自己构建race-it时,我不断得到方法未定义的错误。我找了一些类似的东西,但什么也没找到。learningruby.com对此有一些迂回的答案,但没有告诉我我遗漏了什么。 等级马 @@list_of_horses = [] attr_accessor :name attr_accessor :position def initialize

我正在为一个小游戏创建一个代码,该游戏由4匹马在终端上跑一段设定的距离组成。我把它放在输出我添加的马和我的用户马的地方,但是当我去下一个类自己构建race-it时,我不断得到方法未定义的错误。我找了一些类似的东西,但什么也没找到。learningruby.com对此有一些迂回的答案,但没有告诉我我遗漏了什么。 等级马

  @@list_of_horses = []

  attr_accessor :name
  attr_accessor :position

  def initialize
    self.name = nil
    self.position = 0
  end

  def self.add_horse(*horse_variables)
    horse = Horses.new

    horse.name = horse_variables[0]

    @@list_of_horses.push horse
  end

  def self.add_user(*user_variables)
    add_user = Horses.new
    add_user.name = user_variables[0]

    @@list_of_horses.push add_user
  end


  def self.display_data
    puts "*" * 60
    @@list_of_horses.each do |racer|
        print "-" * racer.position
        puts racer.name
                           end
  end

  def move_forward
    self.position += rand(1..5)
  end


  def self.display_horses
    @@list_of_horses
  end
end


horse1 = Horses.add_horse ("Jackrabbit")
horse2 = Horses.add_horse ("Pokey")
horse3 = Horses.add_horse ("Snips")
user1 = Horses.add_user ("Jim")

Horses.display_data
现在,当我运行这个文件时,它将在我的

野兔

可怜的

剪断

吉姆

但是,当我开始尝试在下一个Race类中调用我在Horses类中创建的方法时,甚至在Race类本身之外,我返回了未定义的方法

require_relative 'Horses_class.rb'

no_winner = true

class Race 

      def begin_race
    puts "And the Race has begun!"
  end


end

while no_winner == true
puts begin_race
racing = Race.new
racing.Horses.display_data


end
那么为什么不允许我调用其他方法呢?我应该使用splat,还是我遗漏了一些更简单的东西?提前谢谢你

Jim

当您调用begin\u race方法时,它似乎超出了范围。您需要使用两种方法之一。或::scope操作符来访问它

class Race
    def self.begin_race
        puts "And the race has begun!"
    end
end

Race::begin_race
# or
Race.begin_race
另外,当您调用racing.Horses.display_data时,您必须确保您的马类是您的racing类的子类。不能通过对象调用子类,必须通过类常量调用它

class Race
    class Horses
        def self.display_data
            puts "The Data"
        end
    end
end

# Access 'display_data'
Race::Horses.display_data
因此,在这种情况下,您的require_relative应该在您的种族类别中,而while块应该如下所示

while no_winner == true
    Race.begin_race
    Race::Horses.display_data
end

这是有道理的,但是为什么在我的while循环中我不能从Horses\u class.rb调用其他方法呢?这是因为你的类不是嵌套的。您必须从您的种族类别中调用require_亲戚。我编辑它来解释上面的内容。