加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby Switch中的返回命令?

发布时间:2020-12-17 01:48:12 所属栏目:百科 来源:网络整理
导读:我想从我的Case语句返回一个值,我需要执行多行代码,因此“then”对我不起作用.使用Return退出Case语句所在的函数.是否有一个关键字可以帮助我的代码清楚地暗示我返回的内容而不仅仅是在最后一行放一个值? complexity = case(scale) when "gtp" x = [various
我想从我的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

解决方法

根据各行代码中发生的情况,您可以将其重构为多种方法:

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
...

当然,一旦你有了这个,你就可以放弃这个案例,转而使用一个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),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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读