scott
scott

Reputation: 43

Ruby switch statement with strings

For some reason this switch statement isn't behaving as I expected:

aString = "DATE MODIFIED"

case aString
    when "DATE MODIFIED"
    => Never gets here
end

But this works

aString = "DATE"
case aString
    when "DATE"
    => Does get here
end

Can anyone explain why, and provide a way to use strings with spaces inside a switch?

Thanks

Upvotes: 3

Views: 9210

Answers (1)

knut
knut

Reputation: 27875

Like Chuck mentioned in his comment, I can't duplicate the behavior you're asking about.

One possible reason for errors like this: One or more spaces between DATE and MODIFIED.

Solution: Check with an regular expression:

[ 
  "DATE MODIFIED",
  "DATE  MODIFIED", #2 spaces
].each{|aString|
  print "Check #{aString}: "
  case aString
      when "DATE MODIFIED"
        puts "Exact hit with one space"
      #without \A/\Z the string could be part of a longer String
      when /\ADATE\s+MODIFIED\Z/ 
        puts "hit with one or more spaces"
  end
}

Another often made error: The String is read from stdin and includes a newline. Solution: Use a regex or check with String#chomp (or String#split if you want to ignore leading and trailing spaces)

Upvotes: 7

Related Questions