Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我今天一直在重构一些代码,并且通过大量使用return. 我想到的一件事是,我很少看到在示例代码、博客文章等中使用 return,这让我认为我做错了什么。
return
在 Ruby 中使用 return 不是惯用的吗?我是否应该让我的方法只通过if/ else,case/when语句返回最终值,而不是提前中断它们return?
if
else
case
when
Ruby 的核心是只在需要时使用 return 。如果提前终止返回使您的方法更清晰,请执行此操作。换句话说:
做:
def method(arg) if(arg == 0) #Special case return 42 end arg + 46 end
不:
def method(arg) return arg + 46 end
最好的:
def method(arg) if(arg == 0) 42 else arg + 46 end end
但是,仅在不必要时才不鼓励 return 。