ruby - 默默换个类?在 Ruby 中可能吗

标签 ruby class

我开发了技术绘图解决方案的类(class)。我必须使用几何基元。例如:

# all specifications are left, bottom and width, height
class Circle
                      #  +--- this is for my later question
                      #  v 
   def initialize(x,y,w,h=w) # left, bottom and w=x+2*radius
      ...
   end
end
# the Ellipse needs 4 specifications (no rotation here)
class Ellipse
   def initialize(x,y,w,h) # left, bottom and w=2*a, h=2*b
      ...
   end
end

如果有人会使用类似的东西

primitive=Cricle.new(10,10,20,30) # note different width and height 

是否可以返回一个椭圆(有点像:“在你接受的事情上保持自由......” Jon Postel 的稳健性原则)?

我认为只要 include Ellipse 就可以解决问题,因为 Circle 和 Ellibse 或多或少相等,我没有尝试这样做,但这会改变 class.name ,如果我这样做的话(在 Ruby 中)会发生什么?

最佳答案

是的,您可以(在Circle类中只需添加以下内容):

def self.new(x, y, w, h)
  return Ellipse.new(x, y, w, h) if w != h
  super
end

重点是,是的,就像你说的那样,这是非常糟糕的做法。在这种情况下,您可以更好地组织事情,并且您通常不应该最终编写这样的 hack。这是一个例子:

class Ellipse
    def initialize(x, y, w, h = w)
        # (x, y) is the origin point
        # w = width, h = height
        # ...
    end
end

class Circle < Ellipse
    def initialize(x, y, d)
        # (x, y) is the origin point
        # d = diameter
        # ...
        super x, y, d, d
    end
end

事实上,圆是椭圆的特例。通过执行上述操作,您可以通过在 Circle#initialize 方法中专门化 Ellipse 的构造函数来明确说明。

关于ruby - 默默换个类?在 Ruby 中可能吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18046946/

相关文章:

javascript - ruby on Rails 4.2.6 "delete action"不工作

javascript - js 按类在按钮上堆叠

class - 如何将 Map 转换为 Scala 中的案例类?

Ruby 依赖注入(inject)库

ruby-on-rails - self 在 ruby​​ on rails 中做什么?

ruby - 使用 mongomapper 时使用 "or"语句

c++ - 你应该为类格式化 operator<< 吗?

Ruby Kernel.raise 方法在将参数括在括号中时抛出错误

java - Mongo Java 驱动程序找不到接口(interface)的公共(public)构造函数

Python 类 __init__ 布局?