ruby - 一个超类,2个子类和一个常用方法 - 出错

问题描述 投票:-3回答:1

以下是Universe(超类),Common(模块),FlatEarthBelievers(子类)和RoundEarthBelievers(子类)。输出有错误并想让它工作,任何指针?

这是关于继承和mixins的情况,其中子类继承自公共Parent并且想要使用与Parent的行为无关的常用方法。我希望能够从包含/扩展它的Child类中的公共模块调用方法。我对它的用法感到困惑,因为我希望将这些常用方法看作类方法和实例方法。

 class Universe
      $knowledge = "Universe comprises of galaxies, stars, planets,  steroids, meteoroids, comets, etc"
       def  universe_comprises_of
       puts $knowledge
     end
    end

    ​module Common
      $earth_is = Hash.new
      def init(earth_is)
        $earth_is = earth_is
      end
       def statement
         puts  " Earth is " + $earth_is["attribute"].to_str
       end
    end

    class FlatEarthBelievers < Universe
      include Common
      earth_is = { :attribute => "Flat !" }
      init(earth_is)
    end

    class RoundEarthBelievers < Universe
       include Common
       earth_is = { :attribute => "Round like an Orange!" }
       Common.init(earth_is)
    end

    moron = FlatEarthBelievers.new
    moron.universe_comprises_of
    moron.statement

    sensible_person = RoundEarthBelievers.new
    sensible_person.universe_comprises_of
    sensible_person.statement
ruby-on-rails ruby subclass mixins superclass
1个回答
0
投票

这段代码有很多问题。抛开$变量问题,因为在你的OP的评论中讨论了这个问题。

首先,你做:

moron = Flat_earth_believers.new

但是你没有任何名为Flat_earth_believers的类。你可能意味着FlatEarthBelievers

include Common模块,它使其中的所有方法实例方法,但是你尝试将它们称为类方法,在这里:

class FlatEarthBelievers < Universe
  include Common
  earth_is = { :attribute => "Flat!" }
  init(earth_is) # this is calling a class method
end

和这里:

class RoundEarthBelievers < Universe
  include Common
  earth_is = { :attribute => "Round like an Orange!" }
  Common.init(earth_is) # this is calling a class method
end    

还有其他的东西,但你明白了。

无论如何,我真的不知道你想要做什么,但我想我会让Universe像:

class Universe
  KNOWLEDGE = "Universe comprises of galaxies, stars, planets,  steroids, meteoroids, comets, etc"

  def  universe_comprises_of
    puts KNOWLEDGE
  end
end

Common像:

module Common

  def statement
    puts "Earth is #{self.class::EARTH_IS[:attribute]}"
  end  

end

然后FlatEarthBelievers喜欢:

class FlatEarthBelievers < Universe
  include Common

  EARTH_IS = { :attribute => "Flat!" }
end

然后你可以这样做:

moron = FlatEarthBelievers.new
moron.universe_comprises_of
 => Universe comprises of galaxies, stars, planets,  steroids, meteoroids, comets, etc
moron.statement
 => Earth is Flat!

我还要注意到Jörg W Mittag希望说:

我是Ruby Purists之一,他们喜欢指出Ruby中没有类方法。但是,我完全没问题,通俗地使用术语类方法,只要所有各方都完全理解它是口语用法。换句话说,如果你知道没有类方法这样的东西,并且术语“类方法”只是“作为Class实例的对象的单例类的实例方法”的缩写,那么就有了没问题。但除此之外,我只看到它阻碍理解。

让所有各方充分理解术语类方法在其口语意义上的使用。

© www.soinside.com 2019 - 2024. All rights reserved.