Mik*_*ter 3 ruby return-value switch-statement
我想从我的Case语句返回一个值,我需要执行多行代码,因此"then"对我不起作用.使用Return退出Case语句所在的函数.是否有一个关键字可以帮助我的代码清楚地暗示我返回的内容而不仅仅是在最后一行放一个值?
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
Run Code Online (Sandbox Code Playgroud)
没有关键字可以从caseRuby中的语句显式标记返回的值.
您可以明确地分配给变量,您已经在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
Run Code Online (Sandbox Code Playgroud)
如果这对您不起作用,那么可以使用其他可能完全避免使用的构造case,或者您可以将多行构造移动到其他方法甚至是包含x和的类中complexity.这是否可以改善您的代码更多是https://codereview.stackexchange.com/的主题- 它将取决于更高级别的事情,例如您的比例类别是否出现在其他地方.
根据各行代码中发生的情况,您可以将其重构为多种方法:
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
...
Run Code Online (Sandbox Code Playgroud)
当然,一旦你拥有了这个,你可以放弃case赞成一个lambdas的哈希:
complexities = {
'gtp' => lambda { ... },
...
}
complexities.default_proc = lambda do |h, scale|
lambda { error "Scale not recognized: #{scale}" }
end
complexity = complexities[scale].call
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢这些方法,请使用哈希方法:
complexities = {
'gtp' => method(:gtp_complexity),
...
}
complexities.default_proc = lambda do |h, scale|
lambda { error "Scale not recognized: #{scale}" }
end
complexity = complexities[scale].call
Run Code Online (Sandbox Code Playgroud)
或者使用实例本身作为查找表和白名单:
complexity = if(respond_to?("#{scale}_complexity"))
send("#{scale}_complexity")
else
error "Scale not recognized: #{scale}"
end
Run Code Online (Sandbox Code Playgroud)