ruby - 处理许多 if 条件的更好方法?

标签 ruby design-patterns

我们有许多不同类型的提要。一个提要有很多 feed_comments。根据提要类型,我想返回一个特定的字符串。

if feed.type == 1
  if nested_comment
    str = "test"
  else if comment
    str = "test1"
  else
    str = "test2"
  end 
else if feed.type == 2
  if nested_comment
    str = "test3"
  else if comment
    str = "test4"
  else
    str = "test5"
  end 
else if feed.type == 3
  if nested_comment
    str = "test6"
  else if comment
    str = "test7"
  else
    str = "test8"
  end 
else if feed.type == 4
  if nested_comment
    str = "test9"
  else if comment
    str = "test10"
  else
    str = "test11"
  end 
end

编写上述代码的更好方法是什么,以便将来如果我们有更多条件时,我不必更改现有代码?

最佳答案

要获得更易于管理和可读的代码,您可以尝试 case statements .除此之外,我看不出您还能如何压缩代码,因为正如有人指出的那样,每种可能性都有不同的结果。

case feed.type
when 1
  case
  when nested_comment then str = "test"
  when comment        then str = "test2"
  else                     str = "test3"
  end
when 2
  case
  when nested_comment then str = "test"
  when comment        then str = "test2"
  else                     str = "test3"
  end
 # repeat for each feed number type
end

关于ruby - 处理许多 if 条件的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663257/

相关文章:

Ruby 提示 nokogiri libiconv.2.dylib

ruby - 如何在 Ruby 1.9 的 ruby​​ 程序中以编程方式调用 ruby​​ 调试器?

c# - 依赖注入(inject)如何帮助对象组合?

java - 需要根据输入字符串调用多个EJB

c++ - 避免在多线程环境中删除单例

node.js - 如何比较图像并确定哪个内容更多?

ruby - 如何使这个正则表达式更通用?

ruby - 最佳实践 : Text-search in Ruby, 还是让 MongoDB 来做这项工作?

php - 为什么 __destruct 中的逻辑

api - 使用 websockets 设计 API 的最佳方式是什么?