gpt4 book ai didi

ruby - 检查 Object 是否为 nil 并且所需的属性是否为 nil 或为空

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:58 25 4
gpt4 key购买 nike

我正在寻找“优雅”的方法来检查给定对象是否为 nil 以及它的属性是否为 nil 或空。目前我有这张支票

response = foo.call() # some service call, no http code given :)
raise StandardError, "Response is not valid" if response.nil? || response['data'].nil? || reponse['data'].emtpy?

有没有更优雅的方法来做到这一点,并避免三重或检查?在 begin/catch 中包装并不是一种优雅的方式,以防有人建议这样做。

最佳答案

这个呢?

data = response.try(:[], 'data')
raise Exception, "Response is not valid" if data.nil? || data.empty?

正如@ksol 在评论中正确提到的那样,try 助手来自 ActiveSupport。但是重新实现一点也不难。

class Object
def try method, *args
if respond_to? method
send method, *args
else
nil
end
end
end

class Foo
def hello name
"hello #{name}"
end
end

f = Foo.new
f.try(:bar) # => nil
f.try(:hello, 'world') # => "hello world"
nil.try(:wat) # => nil

备选方案

这是 Object#andand如果您不想拖延整个 activesupport 并且不想编写已经编写的代码。

data = response.andand['data']
raise Exception, "Response is not valid" if data.nil? || data.empty?

关于ruby - 检查 Object 是否为 nil 并且所需的属性是否为 nil 或为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362139/

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