开发者

Parent and child class hierarchy

开发者 https://www.devze.com 2023-04-03 05:14 出处:网络
So I have many child classes that will inherit from a parent class. I\'ve been playing around with instance variables @ and class variables @@ and I have yet to be able to achieve with them what I wan

So I have many child classes that will inherit from a parent class. I've been playing around with instance variables @ and class variables @@ and I have yet to be able to achieve with them what I want. What I want actually works with the code below but it doesn't seem DRY at all. Any suggestions on how I can refactor this?

class Planet
    def has_color?(color)
        self.color == color
    end

    def has_position?(position)
        self.position == position
    end
end

class Mars < Planet
    def color
        "red"
    end 

    def position
        4
    end
end

class Earth < Planet
    def color
        "blue"
    end

    def position
        3
    end
end

What I hope to achieve

>> Mars.has_color?("red")
true
开发者_如何学运维
>> Earth.position
3


There seems to be no reason for your specific planets (like Earth) to be types at all: Earth is not a family of related planets, it is merely a single planet. You may be better served by a set of constants:

class Planet
  attr_reader :color, :position

  def initialize(color, position)
    @color, @position = color, position
  end

  # If you really want these..
  def has_color?(color)
    @color == color
  end

  def has_position?(position)
    @position == position
  end
end

MARS = Planet.new("red", 4)
EARTH = Planet.new("blue", 3)

MARS.has_color?("red")
EARTH.position

If creating global constants bothers you, by all means wrap them in a module (perhaps Planets?)


is this useful for you ? I have tried , it works in Ruby1.9.2

    class Planet
        def self.has_color?(color)
            @color == color
        end

        def self.has_position?(position)
            @position == position
        end

        def self.position
            @position
        end

        def self.color
            @color
        end
    end

    class Mars < Planet
            @color="red"
            @position=4
    end

    class Earth < Planet
            @color="blue"
            @position=3
    end

    puts Mars.has_color?("red")
    puts Mars.has_position?("3")
    puts Earth.position
    puts Earth.color
0

精彩评论

暂无评论...
验证码 换一张
取 消