2

是否可以使用 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 "%%"
4

5 回答 5

6
case
  when (a % 3).zero? then puts "%3"
  when (a % 4).zero? then puts "%4"
  when (a % 7).zero? && (a % 13).zero? then puts "%%"
end
于 2010-01-19T11:39:25.727 回答
3

当然:

case
when (a%3 == 0) then puts "%3"
when (a%4 == 0) then puts "%4"
when (a%7 == 0 && a%13 == 0) then puts "%%"
end

也好不了多少,不是吗?;-)

于 2010-01-19T11:39:15.000 回答
2
puts [3,4,91,10].collect do |a|
 case 0
 when a % 3 then
  "%3"
 when a % 4 then
  "%4"
 when a % 91 then
  "%%"
 end
end

您应该能够将该权限复制到 irb 以查看它的工作原理。请原谅轻微的 7*13 = 91 hack,但如果您使用实际模数,它们应该是等效的。

于 2010-01-19T23:07:13.060 回答
1

使用过程#===

def multiple_of( factor )
  lambda{ |number| number.modulo( factor ).zero? }
end

case a
  when multiple_of( 3 ): puts( "%3" )
  when multiple_of( 4 ): puts( "%4" )
  when multiple_of( 7*13 ): puts( "%%" )
end
于 2010-01-20T07:40:00.710 回答
0

(a%7 == 0 && a%13 == 0) 等于 (a%7*13 == 0)。

在 ruby​​ 中,您可以使 1 行 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

它看起来很敏捷但很短。

于 2010-01-19T13:42:53.340 回答