Ruby Switch中的返回命令?

时间:2014-05-21 21:46:39

标签: ruby switch-statement return-value

我想从我的Case语句返回一个值,我需要执行多行代码,以便"然后"不适合我。使用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

2 个答案:

答案 0 :(得分: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,或者您可以将多行构造移动到其他方法或甚至是包含{ {1}}和x。这是否可以改善您的代码更多是https://codereview.stackexchange.com/的主题 - 它将取决于更高级别的内容,例如您的比例类别是否出现在其他位置。

答案 1 :(得分: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
...

当然,一旦你拥有了这个,你就可以放弃case,而不是哈利的lambdas:

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

complexity = complexities[scale].call

或者如果您更喜欢这些方法,请使用Hash of methods:

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