2013-02-26 57 views
0

有一個代碼Ruby:該case語句=〜&&〜在 '何時' 狀態

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

否則如果版本正常工作:

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 

將'& &'替換爲逗號會導致錯誤。逗號工作不正確。如何避免這種情況?

回答

1

變化的情況下的順序:

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 
+0

輝煌!我應該想到。感謝重構順便說一句。 – user1201917 2013-02-26 20:45:04

2

您case語句應該是這樣的:

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