gpt4 book ai didi

Ruby 扩展 NilClass

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

我正在尝试为应用程序扩展 Ruby 的 NilClass,以便任何方法调用都将返回 nil(实际上是 self,新的扩展 nil)。目的是避免大量额外的 nil 检查逻辑,例如,

results = data.nil? nil : data.process()
output = results.nil? nil : results.format()

并简单地用

替换它
output = data.process().format()

如果链中的任何地方返回 nil 结果,它将返回 nil。

让类响应任意消息很容易:

class SuperNil
def method_missing(sym, *args)
return self
end
end

现在,supernil = SuperNil.new; supernil.anything 返回对象 supernil。但是,这并不是真正的 nil,因为它的计算结果为 true。以某种方式扩展 NilClass 以便我的对象评估为 false 是否有效?我遇到麻烦的地方是,即使在扩展 NilClass 之后,我也无法创建 SuperNil 的对象。 NilClass.new 报错,SuperNil.new 也报错。

是否可以创建 NilClass 扩展的对象?它会评估为 false 吗?

最佳答案

尝试:

class NilClass
def hello
'hello'
end

def method_missing *args
self
end
end

nil.hello #=> 'hello'
nil.non_existing_method #=> nil

然而,这可能是个坏主意,因为 undefined method for nil 是最有用的异常之一——它表示你在意想不到的地方得到了 nil。相反,您应该指定您知道可能出现 nil 的所有位置 - 看看 'andand' gem,它完全满足需要:

data.nil? nil : data.process()

# is the same as
data && data.process()

# what justifies the name of the gem
data.andand.process()

更新:

不可能创建 nil 的子类的原因很简单——NilClass 不允许创建新实例,它的 new 方法是未定义的(所有不可变的都会有同样的问题Fixnum、Symbol 或 TrueClass 等类)。所以:

class SuperNil < NilClass
def method_missing
self
end
end

不会引发任何问题,但您将无法创建此类的任何实例。

关于Ruby 扩展 NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21049122/

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