2014-05-21 28 views
3

我想從我的Case語句中返回一個值,我需要執行多行代碼,所以「then」對我不起作用。使用Return可以退出Case語句所在的函數。是否有一個關鍵字能夠幫助我的代碼清楚地意識到我正在返回的內容,而不會在最後一行中添加值?在Ruby Switch中返回命令?

complexity = case(scale) 
    when "gtp" 
    x = [various lines of code] 
    x = [various lines of code] 
    10 
    when "preSi" 
    x = [various lines of code] 
    x = [various lines of code] 
    30 
    when "postSi"  
    x = [various lines of code] 
    x = [various lines of code] 
    40 
    else 
    error"Scale not recognized: #{scale.to_s}" 
    end 
+0

那麼爲什麼不直接使用'與任何/無論你正在返回的東西return'關鍵字? – kiddorails

+0

「return」退出我正在使用這個case語句的函數。 –

回答

6

根據在代碼各種線發生什麼事,你可以重構它分成幾個方法:

complexity = case(scale) 
    when 'gtp' then gtp_complexity 
    when 'preSi' then preSi_complexity 
    ... 
end 

# and elsewhere... 
def gtp_complexity 
    x = [various lines of code] 
    x = [various lines of code] 
    10 
end 
... 

當然,一旦你有了這個,你可以贊成lambda表達式的散列溝case

complexities = { 
    'gtp' => lambda { ... }, 
    ... 
} 
complexities.default_proc = lambda do |h, scale| 
    lambda { error "Scale not recognized: #{scale}" } 
end 

complexity = complexities[scale].call 

或者,如果你喜歡的方法更好,使用的方法哈希:

complexities = { 
    'gtp' => method(:gtp_complexity), 
    ... 
} 
complexities.default_proc = lambda do |h, scale| 
    lambda { error "Scale not recognized: #{scale}" } 
end 

complexity = complexities[scale].call 

或使用該實例本身作爲你的查找表和白名單:

complexity = if(respond_to?("#{scale}_complexity")) 
    send("#{scale}_complexity") 
else 
    error "Scale not recognized: #{scale}" 
end 
+0

我選擇了你的答案,並不是因爲我會在這個特定的代碼中使用你的建議,而是因爲你給了我一些很好的例子來說明如何更好地編寫Ruby方法。很有創意,謝謝。 –

6

無有不從在Ruby中case聲明明確標註返回值的關鍵字。

可以明確地分配給變量,你已經在做與x,想必使用局部變量進一步下降,這是沒有什麼不同:

case(scale) 
    when "gtp" 
    x = [various lines of code] 
    x = [various lines of code] 
    complexity = 10 
    when "preSi" 
    x = [various lines of code] 
    x = [various lines of code] 
    complexity = 30 
    when "postSi"  
    x = [various lines of code] 
    x = [various lines of code] 
    complexity = 40 
    else 
    error "Scale not recognized: #{scale.to_s}" 
    end 

如果不爲你工作,那麼其他結構可用,可能完全避免使用case,或者您可以將多線結構移動到其他方法或甚至包含xcomplexity的類中。這是否可以改善您的代碼更多是https://codereview.stackexchange.com/的主題 - 它將取決於更高級別的事情,例如您的規模類別是否出現在其他地方。

+1

這很有道理,因爲這種情況下的表達式不是純粹的表達式。讓它既設置變量又產生一個值是有點奇怪的。這樣你只能設置變量,這更清晰。 – Chuck

+0

非常感謝這個建議。看起來比我所擁有的更好。 –