Ruby取消对象创建

Ruby取消对象创建,ruby,object,constructor,Ruby,Object,Constructor,如果参数错误,如何取消对象创建? 例如: 很简单,只是不要使用构造函数。:) 顺便说一句,这种模式称为工厂方法。除非您需要某种静默故障模式来处理坏数据,否则您可能只想引发错误并停止程序: def initialize(a, b, c) @a = @b = @c = nil raise "First param to new is not an Integer" unless a.is_a? Integer @a = a raise "Second param

如果参数错误,如何取消对象创建? 例如:


很简单,只是不要使用构造函数。:)


顺便说一句,这种模式称为工厂方法。

除非您需要某种静默故障模式来处理坏数据,否则您可能只想引发错误并停止程序:

def initialize(a, b, c)
    @a = @b = @c = nil

    raise "First param to new is not an Integer" unless a.is_a? Integer
    @a = a

    raise "Second param to new is not a String" unless b.is_a? String
    @b = b

    raise "Third param to new is not an Integer or Float" unless c.is_a? Integer or c.is_a? Float
    @c = c
end
您是使用这种方法,还是使用传递错误输入的工厂方法取决于您希望处理的数据类型


就我个人而言,我几乎总是会提出错误,除非我有一个特定的要求,默默地忽略坏数据。但这是编码原理,不一定是解决您问题的最佳答案。

可能使用工厂方法模式,以便外部方法检查有效参数,如果失败,则返回nil,而不是初始化对象。
self.make
可以改进为:
def self.make(a,b,c);返回,除非a.is_a?(整数)和b.is_a?(字符串)以及c.is_a?(整数)| c.is_a?(浮点);新的(a,b,c)结束
+1,但我要说明始终使用异常的理由:如果您真的需要默默地忽略错误的输入,那么将异常包装在
rescue
子句中是一种方法。
class MyClass
  def initialize(a, b, c)
    @a, @b, @c = a, b, c
  end

  def self.fabricate(a, b, c)
    aa = a if a.is_a? Integer
    bb = b if b.is_a? String
    cc = c if c.is_a? Integer || c.is_a? Float
    return nil unless aa && bb && cc
    new(aa, bb, cc)
  end
end

cl = MyClass.fabricate('str', 'some', 1.0) # => nil
def initialize(a, b, c)
    @a = @b = @c = nil

    raise "First param to new is not an Integer" unless a.is_a? Integer
    @a = a

    raise "Second param to new is not a String" unless b.is_a? String
    @b = b

    raise "Third param to new is not an Integer or Float" unless c.is_a? Integer or c.is_a? Float
    @c = c
end