开发者

Ruby Convert If Statements to Case

Is it possible to use a case statement to replace these if statements?

if (a%3 == 0) then puts "%3"
elsif (a%4 == 0) then puts "%4"
elsif (a%7 == 0 && a%13 == 0) then put开发者_StackOverflow社区s "%%"


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


Sure:

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

It isn't much better, is it? ;-)


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

You should be able to copy that right into irb to see it work. Please forgive the slight 7*13 = 91 hack, but if you're working with actual modulos they should be equivalent.


Using Proc#===

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


(a%7 == 0 && a%13 == 0) is equal to (a%7*13 == 0).

in ruby, you can make 1-line if-else statement use && and ||.

puts (a%3 == 0)&&"%3"||(a%4 == 0)&&"%4"||(a%(7*13) == 0)&&"%%"||""

or

log = (a%3 == 0)&&"%3"||(a%4 == 0)&&"%4"||(a%(7*13) == 0)&&"%%"
puts log if log

it's looks agly but short.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜