如何在Ruby中减少long if条件?

时间:2011-11-26 19:51:54

标签: ruby-on-rails ruby

在Ruby中写条件的最佳方法是什么?

if (    $response_code == "400" ||
        $response_code == "401" ||
        $response_code == "402" ||
        $response_code == "403" ||
        $response_code == "404" ||
        $response_code == "411" ||
        $response_code == "500" ||
        $response_code == "501" ||
        $response_code == "502" ||
        $response_code == "0")
    {
        return false;
    }

Ruby似乎有简洁的做事方式,所以想知道我是否可以避免写这么长的东西。

4 个答案:

答案 0 :(得分:7)

可能的解决方案:

ACCEPTED_CODES = [ "400", "401", "402", "403", "404", "411", "500", "501", "502", "0" ]

def test(response_code)
  !ACCEPTED_CODES.include?(response_code)
end

答案 1 :(得分:4)

  case $response_code.to_i
  when 400, 401, 402, 403, 404, 411, 500, 501, 502, 0
    return false
  end

答案 2 :(得分:1)

if [400, 401, 402, 403, 404, 411, 500, 501, 502, 0].include?($response_code.to_i)

end

答案 3 :(得分:1)

CODES = [400, 401, 402, 403, 404, 411, 500, 501, 502, 0]

return CODES.exclude? $response_code.to_i