开发者

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 switc开发者_运维百科h?

Thanks


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜