ruby - 重构 if else 语句 [英] ruby - refactoring if else statement

查看:39
本文介绍了ruby - 重构 if else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试阅读一些有关重构的教程,但我在条件方面苦苦挣扎.我不想使用三元运算符,但也许应该在方法中提取它?或者有什么聪明的使用地图的方法?

I've tried reading some tutorials on refactoring and I am struggling with conditionals. I don't want to use a ternary operator but maybe this should be extracted in a method? Or is there a smart way to use map?

detail.stated = if value[:stated].blank?
                  nil
                elsif value[:stated] == "Incomplete"
                  nil
                elsif value[:is_ratio] == "true"
                  value[:stated] == "true"
                else
                  apply_currency_increment_for_save(value[:stated])
                end

推荐答案

如果你将此逻辑移到一个方法中,由于早期的 return(和关键字参数),它可以变得更清晰:

If you move this logic into a method, it can be made a lot cleaner thanks to early return (and keyword arguments):

def stated?(stated:, is_ratio: nil, **)
  return if stated.blank? || stated == "Incomplete"
  return stated == "true" if is_ratio == "true"
  apply_currency_increment_for_save(stated)
end

那么……

detail.stated = stated?(value)

这篇关于ruby - 重构 if else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆