是否可以使用case语句来替换这些if语句?
if (a%3 == 0) then puts "%3"
elsif (a%4 == 0) then puts "%4"
elsif (a%7 == 0 && a%13 == 0) then puts "%%"发布于 2010-01-19 21:42:53
(a%7 == 0 && a%13 == 0)等于(a%7*13 == 0)。
在ruby中,您可以使用&&和||来编写一行if-else语句。
puts (a%3 == 0)&&"%3"||(a%4 == 0)&&"%4"||(a%(7*13) == 0)&&"%%"||""
或
log = (a%3 == 0)&&"%3"||(a%4 == 0)&&"%4"||(a%(7*13) == 0)&&"%%"
puts log if log它看起来很漂亮,但很短。
https://stackoverflow.com/questions/2092905
复制相似问题