Ruby - Case Statement帮助

时间:2011-02-28 01:15:13

标签: ruby-on-rails ruby ruby-on-rails-3

我的案例陈述有点像这样:

case @type
 when "normal"

 when "return"

 else
end

工作正常,但我想添加类似的内容:

case @type
 when "normal"

 when "return"

 when @type length > 1, and contains no spaces

 else
end

这有效/安全吗?

3 个答案:

答案 0 :(得分:4)

如果你没有匹配@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

答案 1 :(得分:1)

也许这个?

@type[/^[^\s]{2,}$/]

答案 2 :(得分:1)

您可以输入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

[^ ]表示“除了空格之外的任何东西”,[^ ][^ ]+表示“除了空格后跟一个或多个不是空格的字符的任何东西”,将正则表达式固定在两端确保存在根本不会有任何空间。

相关问题