如何使用Ruby访问Polymorphism中的变量?

时间:2019-07-08 10:01:08

标签: ruby-on-rails ruby

我试图在每种多态方法中访问size变量。运行代码时,出现以下错误:

examples.rb:181:in `calculate_area': undefined method `/' for nil:NilClass (NoMethodError)
        from examples.rb:175:in `calculate_area'
        from examples.rb:199:in `<main>'

我尝试了无数次黑客攻击,但仍未提出好的解决方案。这是下面的代码。

class Shape    

    attr_accessor :size

    def calculate_area(shape_type)
        shape_type.calculate_area
    end
end

class Circle < Shape
    def calculate_area
        return Math::PI * (size / 2) * (size / 2)
    end
end

class Square < Shape
    def calculate_area
        return size * size
    end
end

class Triangle < Shape
    def calculate_area
        return 0.5 * (size * 2) * size
    end
end

shape = Shape.new
shape.size = 5
puts shape.calculate_area(Circle.new)
puts shape.calculate_area(Square.new)
puts shape.calculate_area(Triangle.new)

1 个答案:

答案 0 :(得分:6)

您以错误的方式运行它。您应该创建具体形状的实例,然后在其上调用方法:

[8] pry(main)> circle = Circle.new
=> #<Circle:0x0000563ed7328770>
[9] pry(main)> circle.size = 5
=> 5
[10] pry(main)> circle.calculate_area
=> 12.566370614359172