gpt4 book ai didi

Ruby 取消对象创建

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:50 24 4
gpt4 key购买 nike

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

class MyClass
def initialize(a, b, c)
@a = @b = @c = nil
@a = a if a.is_a? Integer
@b = b if b.is_a? String
@c = c if c.is_a? Integer or c.is_a? Float
return nil if @a == nil or @b == nil or @c == nil # doesn't works
end
end
cl = MyClass.new('str', 'some', 1.0) # need cl to be nil because 1st param isn't Integer

最佳答案

很简单,不用构造器就行了。 :)

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

顺便说一句,这个模式叫做工厂方法。

关于Ruby 取消对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com