views:

218

answers:

5

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 puts "%%"
+2  A: 

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? ;-)

Jamie van Dyke
i think it is, slighly =p
verhogen
+4  A: 
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
Simone Carletti
that's not right, it'll print 'Nil' when it does not fall into one of those conditions, which is not what the original code does.
verhogen
You're right. Simply move the puts into the case statement. I changed the answer accordingly.
Simone Carletti
A: 

(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.

marocchino
+2  A: 
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.

Tim Snowhite
A: 

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
Farrel