3

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

1
  • 5
    I can't duplicate the behavior you're asking about. I took your code, filled out the when-clause and ran it and it worked fine. Can you post some actual, runnable code that demonstrates the problem? Commented Sep 19, 2011 at 8:05

1 Answer 1

7

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)

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

1 Comment

Thanks knut! I swear I checked that double space but the application begs to differ =( Thanks for your time

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.