17

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"

9
  • 1
    I can't reproduce this (and it shouldn't happen). Probably your assumption that params[:test] == "bar" is faulty. Commented Mar 25, 2012 at 16:07
  • I've just check it in irb command line and I can't reproduce your situation. "bar" =~ /foo/ returns nil. Your issue is somewhere else... Commented Mar 25, 2012 at 16:10
  • I have Rails.logger.info(params[:test]) the line above the if statement and it outputs "bar" Commented Mar 25, 2012 at 16:13
  • @Exupery: Try Rails.logger.info(params[:test].class). It just can't be that params[:text] == "bar", otherwise your Ruby is buggy, which seems very unlikely. Can you use pry to peek at the current execution index before the if? This will let you debug the current value of params[:test] better than a logging statement (and you can try the regex matching interactively). Commented Mar 25, 2012 at 16:14
  • 2
    Upon further testing it seems the condition is only getting properly evaluated the first time the method is called. Subsequent calls return the same value regardless of what "test" becomes. Obviously I'll need to try and determine what's causing Rails to use the cached value. Thanks to everyone for the assistance. Commented Mar 25, 2012 at 18:16

1 Answer 1

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

hi @michael, could you explain what the "=~" does and other uses? This is new to me and just kinda wanted some understanding.
@RogerPerez See this question Or the docs link mention there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.