Search code examples
rubyor-condition

Ruby multiple OR conditions


In ruby, is there a more concise way of expressing multiple OR conditions in an if statement?

For example this is the code I have:

if call_type == "GPRS" || call_type == "SMS" || call_type == "MMS" || call_type == "USSD" || call_type == "TELEPHONY"
  #do something
end

There will be more OR conditions and I don't want to write like this multiple times. Is there a better way to express this in ruby 2.1.0 ?

Thanks in advance.


Solution

  • You could use Array#include?:

    if %w(GPRS SMS MMS USSD TELEPHONY).include? call_type
      # ...
    end
    

    Or a case expression:

    case call_type
    when 'GPRS', 'SMS', 'MMS', 'USSD', 'TELEPHONY'
      # ...
    end
    

    Or a regular expression:

    if call_type =~ /^(GPRS|SMS|MMS|USSD|TELEPHONY)$/
      # ...
    end
    

    As noted by cremno, ^ and $ match beginning and end of line. You can use \A and \z instead if call_type contains multiple lines.