Using regex in Ruby if condition

39,165
if params[:test] =~ /foo/
    # Successful match
else
    # Match attempt failed
end

Works for me. Debug what is in params[:test]

Share:
39,165
frostmatthew
Author by

frostmatthew

Senior Software Engineer at Disney Streaming building the APIs and services that deliver the content discovery experience for Disney+, ESPN+, and Hulu. Previously at VMware for over seven years working on Cloud Director. matthewfrost.com@frostmatthewLinkedIn

Updated on March 26, 2020

Comments

  • frostmatthew
    frostmatthew about 4 years

    I'm trying to use regex as the conditional in a Ruby (1.9.2) if statement but it keeps returning true even when the regex evaluates to nil

    if (params[:test] =~ /foo/)
      return "match"
    else
      return "no match"
    end
    

    The above returns "match" even when Rails.logger.info(params[:test]) shows test as set to "bar"