Ruby - Case Statement help
I have a case statement that goes a little something like this:
case @type
when "normal"
when "return"
else
end
That works fine but I want to add in something like:
case @type
when "normal"
when "return"
when @type length > 1, and contains n开发者_StackOverflowo spaces
else
end
Is that valid / safe?
if you aren't matching against the value of @type then don't include it right after the case statement, but rather in the when clauses:
case
when @type=="normal" then "blah"
when @type=="return" then "blah blah"
when (@type.length>1 and !@type.include?(' ')) then "blah blah blah"
else
end
maybe this?
@type[/^[^\s]{2,}$/]
You can put a regex in a when
:
case @type
when 'normal' then 'it is normal'
when 'return' then 'it is return'
when /^[^ ][^ ]+$/ then 'it is long enough and has no spaces'
else 'it is something else'
end
The [^ ]
means "anything but a space" and [^ ][^ ]+
means "anything but a space followed by one or more characters that are not a space", anchoring the regex at both ends ensures that there won't be any spaces at all.
精彩评论