加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何写出复杂的条件

发布时间:2020-12-17 03:39:52 所属栏目:百科 来源:网络整理
导读:当您具有简单的条件和可能复杂的主体时,条件结构很容易编写: if simple_condition_expressed_in_one_liner complicated_body_that_may_be_long complicated_body_that_may_be_long complicated_body_that_may_be_longend 但有时,你有一个复杂的条件和一个像
当您具有简单的条件和可能复杂的主体时,条件结构很容易编写:

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

但有时,你有一个复杂的条件和一个像这样的简单的身体:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读