ruby - 重构条件变量赋值

标签 ruby refactoring

我正在做一个项目。目前我有一个相当大的条件语句,它根据一些输入参数为变量赋值。所以,我有这样的东西。

if some condition
  x = some value
elsif another condition
  x = a different value
  ...

重构它的最佳方法是什么?我希望我最终会得到类似的东西

x = some value if some condition || another value if another condition

这种事情有规律吗?

最佳答案

只需将赋值放在 if 之外即可。

x = if some condition
  some value
elsif another condition
  a different value

或者您可以使用哈希。

x = dict[some condition]

关于ruby - 重构条件变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15535831/

相关文章:

perl - 如何重构使用 Template Toolkit 和 DBI 的 Perl 代码以利用 FastCGI?

ruby - 在 rails 3.0.1 中测试自定义路由不起作用,还是我?

ruby - 获取错误 : dyld: Symbol not found: _clock_gettime

html - 使用 Rails 助手嵌套 HTML 元素

ruby - 这个 define_method 用例是不是太复杂了?

language-agnostic - 避免 TDD 使大规模重构变得更加困难

ruby - 在 Jenkins 中运行多个 Cucumber 功能

refactoring - 可怕的 While (True) 循环的最佳重构

java - 如何重构返回嵌套 MAP 的 JAVA 方法?

javascript - 将函数重构为对象方法