Ruby:除非 vs 如果不是

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7520032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:20:37  来源:igfitidea点击:

Ruby: unless vs if not

rubycoding-style

提问by NullVoxPopuli

I find myself preferring if notrather than unless. Is there a proper way to write that sort of condition? How do people generally feel about unless?

我发现自己更喜欢if not而不是unless. 有没有合适的方法来写这种条件?人们普遍感觉如何unless

采纳答案by derp

I hope this helps you:
https://github.com/bbatsov/ruby-style-guide

我希望这对你有帮助:https:
//github.com/bbatsov/ruby-style-guide

I personally agree with what's written there choosing unless somethingover if !somethingfor modifiers and simple ones and when there's an elseprefer if.

我个人有什么写有选择同意unless somethingif !something为改性剂和简单的01时,有一种else偏爱if

回答by jefflunt

I use unlessevery time, except when there is an elseclause.

unless每次都使用,除非有else子句。

So, I'll use

所以,我会用

unless blah_blah
  ...
end

but if there is an else condition, I'll use if not(or if !)

但如果有其他条件,我会使用if not(或if !

if !blah_blah
 ...
else
 ...
end

After using if !for years and years and years, it actually took me a while to get used to unless. Nowadays I prefer it in every case where reading it out loud sounds natural.

使用if !了多年,年复一年,实际上我花了一段时间才习惯unless。现在我更喜欢在任何情况下大声朗读听起来很自然。

I'm also a fan of using a trailing unless

我也喜欢使用尾随 unless

increment_by_one unless max_value_reachedI'm using these method/variable names obviously as a readability example - the code's structure should basically follow that pattern, in my opinion.

increment_by_one unless max_value_reached我显然使用这些方法/变量名称作为可读性示例 - 在我看来,代码的结构应该基本上遵循该模式。

In a broader sense, the structure should be: take_action unless exception_applies

从广义上讲,结构应该是: take_action unless exception_applies

回答by Simone Carletti

if not conditionis rarely used. Ruby programmers (usually coming from other languages) tend to prefer the use if !condition.

if not condition很少使用。Ruby 程序员(通常来自其他语言)倾向于使用if !condition.

On the other side, unless is widely use in case there is a single condition and if it sounds readable.

另一方面,除非在存在单一条件且听起来可读的情况下被广泛使用。

Also see making sense with Ruby unlessfor further suggestions about unless coding style.

另请参阅对 Ruby 的理解,除非有关于除非编码风格的进一步建议。