gpt4 book ai didi

ruby - 在 Ruby 中返回 nil 的惯用方式

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

不显式返回 nil 在 Ruby 中是惯用的吗?让我们这样说:

def find_something data
if data.has_what_we_need?
a = data.something
if a.has_what_we_want?
a.the_stuff[42]
end
end
end

与这样的东西(可以说是嘈杂的)相反:

def find_something data
if data.has_what_we_need?
a = data.something
if a.has_what_we_want?
a.the_stuff[42]
else
nil
end
else
nil
end
end

最佳答案

我尝试创建在不满足条件时尽早退出的方法,在缩进方面扁平化代码:

def find_something data
return unless data.has_what_we_need?

a = data.something

return unless a.has_what_we_want?

a.the_stuff[42]
end

这有两个明确定义的退出点,因为 return 在阅读时应该显示为一个相当明显的东西。没有参数的 return 将返回 nil 给调用者。

如果您不关心 nilfalse 的区别,您可以进一步压缩:

def find_something data
return unless data.has_what_we_need?

a = data.something

a.has_what_we_want? and a.the_stuff[42]
end

关于ruby - 在 Ruby 中返回 nil 的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453877/

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