我发现我经常在我的 Ruby 代码中做这样的事情:
if person
if person.shirt
if person.shirt.sleeve
...
end
end
..我这样做是为了避免 NoMethodErrors
。我想知道是否有任何方法可以将其折叠成一行,而没有明显的
if person && person.shirt && person.shirt.sleeve
基本上,我想让我的代码更紧凑。
最佳答案
在那些 ifs 中你想用袖子做点什么,对吧?
Rails 有一个好 helper ,try
.如果一切顺利,它返回值,否则返回 nil
。因此,在此示例中,如果 person.shirt
甚至 person
本身为 nil,try 也将返回 nil。
if sleeve = person.try(:shirt).try(:sleeve)
# do your stuff
end
对于 Vanilla ruby ,您可以使用 andand
提供类似功能的 gem。
if sleeve = person.andand.shirt.andand.sleeve
# do your stuff
end
自 ruby 2.3 起,您可以使用安全导航运算符:
if sleeve = person&.shirt&.sleeve
# do your stuff
end
关于ruby - 如何最小化嵌套的 if 语句? ( ruby ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11402531/