Ruby 有没有更简洁的方法来编写这段代码

Ruby 有没有更简洁的方法来编写这段代码,ruby,Ruby,我刚刚编写了这个ruby代码,它非常简单,我只想交换依赖于变量的操作顺序。我有一种感觉,我写的东西比它需要的更冗长,有人能想出一种更简洁的写作方式吗 if opts["--appears"] if regex = opts["--matches"] test = !response.text.match(regex) else test = !response.empty? end else if regex = opts["--matches"] tes

我刚刚编写了这个ruby代码,它非常简单,我只想交换依赖于变量的操作顺序。我有一种感觉,我写的东西比它需要的更冗长,有人能想出一种更简洁的写作方式吗

if opts["--appears"]
  if regex = opts["--matches"]
    test = !response.text.match(regex)
  else
    test = !response.empty?
  end
else
  if regex = opts["--matches"]
    test = response.text.match(regex)
  else
    test = response.empty?
  end
end
所以我认为可以优化的是外部if块,所有的变化是它将
test
变成
!测试
。对于这个看似简单的问题,我深表歉意,但我实在想不出该怎么做来优化它

如果您认为这是一个不适合这个问题的论坛,或者您认为它是否应该转移到代码审查,请告诉我。我想这可能是最好的地方,但不确定


谢谢

一个简单的改进是先运行测试,然后返回否定的选项(如果选项[“--出现]):


我相信这将简化代码并提高可读性:

regex = opts["--matches"]
test =
  if opts["--appears"]
    regex ? !response.text.match(regex) : !response.empty?
  else
    regex ? response.text.match(regex)  : response.empty?
  end
或者,如果您愿意:

regex = opts["--matches"]
test =
  case opts["--appears"]
  when true
    regex ? !response.text.match(regex) : !response.empty?
  when false
    regex ? response.text.match(regex)  : response.empty?
  end

或者将第一个if/else组合成一个三元运算符,谢谢,我知道其中有一些非常明显的东西,非常感谢。:)@不过,我不确定staticx是否会提高代码的可读性。如果继续问这个问题会更好。堆栈溢出用于处理代码问题的问题。代码审查是关于改进代码的问题。谢谢,@theTinMan我不确定这就是我在最后一句中问的原因,我以后会在那里发布(我认为这有点边缘化,无法决定)。
regex = opts["--matches"]
test =
  case opts["--appears"]
  when true
    regex ? !response.text.match(regex) : !response.empty?
  when false
    regex ? response.text.match(regex)  : response.empty?
  end