簡體   English   中英

Ruby-案例聲明幫助

[英]Ruby - Case Statement help

我有一個案例聲明,內容如下:

case @type
 when "normal"

 when "return"

 else
end

效果很好,但我想添加以下內容:

case @type
 when "normal"

 when "return"

 when @type length > 1, and contains no spaces

 else
end

那有效/安全嗎?

如果您與@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,}$/]

您可以在以下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

[^ ]表示“除空格外的任何內容”,而[^ ][^ ]+表示“除空格后接一個或多個非空格字符的任何內容”,在兩端固定正則表達式可確保不會完全沒有空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM