ruby - 如何写一个复杂的条件

标签 ruby coding-style conditional-statements

当您有一个简单的条件和一个可能复杂的主体时,条件构造很容易编写:

if simple_condition_expressed_in_one_liner
  complicated_body_that_may_be_long
  complicated_body_that_may_be_long
  complicated_body_that_may_be_long
end

但有时候,你的情况很复杂, body 很简单,就像这样:

if condition1 and
condition2 and
condition3 and
some_more_complicated_condition_that_cannot_be_written_on_a_single_line and
still_some_more_complicated_condition_that_cannot_be_written_on_a_single_line
  simple_body
end

这样的话,有什么好的写法吗?

最佳答案

我总是尝试重构为更小的描述方法。

使用您的示例,而不是:

until (print "Username : "; gets.chomp == "user") and
      (print "Password : "; gets.chomp == "pa$$word")
  puts "Error, incorrect details"
end

我会使用:

def correct_user
  print "Username : "
  gets.chomp == "user"
end

def correct_password
  print "Password : "
  gets.chomp == "pa$$word"
end

until correct_user and correct_password
  puts "Error, incorrect details"
end

关于ruby - 如何写一个复杂的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15883541/

相关文章:

python - 在 Python 中是否可以在 RETURN 语句之后制作一个包含多个 IF 和 OR 的单行代码?

ruby-on-rails - 带 Rails 的 Redis

ruby-on-rails - Rails i18n 方法导致段错误?

if-statement - Stata 中的条件 if 和编程 if

c - break in side for loop - 在 break 语句之后不在 for 循环之外打印任何内容

coding-style - 该字段必须具有文档标题-样式警察-代码有异味?

ruby-on-rails - ruby & :method syntax

ruby-on-rails - 安装 Cucumber 0.93 时出现 "ERROR: Failed to build gem native extension"

c# - 有一个单一的,可能是常见的,通用的异常是不是糟糕的编程风格?

c++ - 使用宏来专门化 std::swap