Ruby:case语句带=〜&& !'在'什么时候'的情况

时间:2013-02-26 18:15:40

标签: ruby switch-statement match

有代码

file_paths = {nature:[], nature_thumb:[]}

Elsif版本运行良好:

 Find.find('public/uploads') do |path|
   if path =~ /.*nature.*\.(jpg|png|gif)$/ and  path !~  /.*nature\/thumb.*\.(jpg|png|gif)$/
     file_paths[:nature] << path
   elsif
     path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
     file_paths[:nature_thumb] << path
     #etc
   end 
 end

案例版本导致问题

 Find.find('public/uploads') do |path|
   case 
   when path =~ /.*nature.*\.(jpg|png|gif)$/, path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/ 
     file_paths[:nature] << path
   when path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
     file_paths[:nature_thumb] << path
     # etc
   end
 end

放置&amp;&amp;&amp;&#39;而是逗号导致错误。逗号错误。怎么避免这个?

2 个答案:

答案 0 :(得分:2)

您的案例陈述应如下所示:

Find.find('public/uploads') do |path|

   case 
       #Surround your statement with parenthesis
       when ((path =~ /.*nature.*\.(jpg|png|gif)$/) && (path !~ /.*nature\/thumb.*\.(jpg|png|gif)$/)) 
         file_paths[:nature] << path
       when path =~ /.*nature\/thumb.*\.(jpg|png|gif)$/
         file_paths[:nature_thumb] << path
         # etc
       end
    end  

答案 1 :(得分:2)

更改案件的顺序:

Find.find('public/uploads') do |path|
  case path
  when /.*nature\/thumb.*\.(jpg|png|gif)$/
    file_paths[:nature_thumb] << path
  when /.*nature.*\.(jpg|png|gif)$/
    file_paths[:nature] << path
  end
end
在您的情况下

或更好:

Find.find('public/uploads') do |path|
  file_paths[
    case path
    when /.*nature\/thumb.*\.(jpg|png|gif)$/ then :nature_thumb
    when /.*nature.*\.(jpg|png|gif)$/        then :nature
    end
  ] << path
end