mha*_*190 2 ruby ruby-on-rails
我正在学习Ruby和RoR,并注意到它不是使用
if !foo
Run Code Online (Sandbox Code Playgroud)
红宝石提供
unless foo
Run Code Online (Sandbox Code Playgroud)
另外,而不是:
while !foo
Run Code Online (Sandbox Code Playgroud)
我们有
until foo
Run Code Online (Sandbox Code Playgroud)
来自C++/Java,当我阅读时,它似乎只会让我感到困惑,除非/直到.看起来好像在ruby中编程的人通常使用除非/直到否定if/while?
这是我应该习惯的东西,还是你看到很多关于这个问题的差异?
谢谢!
是的,使用unless condition而不是if !condition常见且惯用的方法。
unless foo
# ...
end
Run Code Online (Sandbox Code Playgroud)
用作后置条件尤其常见:
# Bad
raise "Not Found" if !file_exists?(file_name)
# Good
raise "Not Found" unless file_exists?(file_name)
Run Code Online (Sandbox Code Playgroud)
如有疑问,请遵循ruby-style-guide
从ruby样式指南的语法部分:
除非是否为负面条件(或控制流量||),否则支持.
# bad
do_something if !some_condition
# bad
do_something if not some_condition
# good
do_something unless some_condition
# another good option
some_condition || do_something
Run Code Online (Sandbox Code Playgroud)
和
在负面条件下支持直到结束.
# bad
do_something while !some_condition
# good
do_something until some_condition
Run Code Online (Sandbox Code Playgroud)