简体   繁体   English

Ruby-案例声明帮助

[英]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: 如果您与@type的值不匹配,则不要在case语句后立即添加它,而要在when子句中添加它:

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 : 您可以在以下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. [^ ]表示“除空格外的任何内容”,而[^ ][^ ]+表示“除空格后接一个或多个非空格字符的任何内容”,在两端固定正则表达式可确保不会完全没有空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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