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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- ruby-on-rails – RubyMine中的简单控制台
- 在Swift属性中要求协议和类
- objective-c – 将工作委托给两个不同的代表,是否
- ruby-on-rails – 资产未在capybara / rspec规范
- ORACLE 11 G 版本 2 RAC 在 LINUX 上使用 NFS 安
- ruby-on-rails – 在rails vist父目录上的NET ::
- C/C++中提高查找速度的小技巧
- React Native 轻松集成分享功能(Android 篇)
- IVY throws IOException Resetting to invalid m
- React Native是怎么在Android上跑起来的
热点阅读