我们有许多不同类型的提要。一个提要有很多 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/