是否可以从父类创建子类的实例?

时间:2016-01-10 15:28:33

标签: ruby inheritance

我尝试在Ruby中定义操作语义,仅用于学习目的。我想定义一些操作:add,multiply,subtraction,division。

这是代码:

class Operation < Struct.new(:left, :right)
  def inspect
    "#{self}"
  end

  def reducible?
    true
  end 
end

class Add < Operation
  def to_s
    "#{left} + #{right}"
  end

  def reduce
    if left.reducible?
      Add.new(left.reduce, right)
    elsif right.reducible?
      Add.new(left, right.reduce)
    else
      Number.new(left.value + right.value)
    end
  end

end

class Multiply < Operation
  def to_s
    "#{left} * #{right}"
  end

   def reduce
    if left.reducible?
      Multiply.new(left.reduce, right)
    elsif right.reducible?
      Multiply.new(left, right.reduce)
    else
      Number.new(left.value + right.value)
    end
  end
end

是否可以使用相同的东西,但在reduce类中定义Operation,但在Operation类中创建某个特定子类的实例?

提前致谢。

1 个答案:

答案 0 :(得分:5)

class Operation
  def reduce
    if left.reducible?
      self.class.new(left.reduce, right)
    elsif right.reducible?
      self.class.new(left, right.reduce)
    else
      Number.new(left.value + right.value)
    end
  end
end