简体   繁体   中英

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 no 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

也许这个?

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM