user1049097
user1049097

Reputation: 1901

How to reduce a long if condition in Ruby?

What's the best way to write following if condition in 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 seems to have concise way of doing things so was wondering if I can avoid writing long stuff like this.

Upvotes: 1

Views: 1093

Answers (4)

KARASZI István
KARASZI István

Reputation: 31477

Possible solution:

ACCEPTED_CODES = %w[400 401 402 403 404 411 500 501 502 0]

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

Upvotes: 8

Victor Moroz
Victor Moroz

Reputation: 9225

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

Upvotes: 4

cmpolis
cmpolis

Reputation: 3051

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

return CODES.exclude? $response_code.to_i

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124800

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

end

Upvotes: 1

Related Questions