Last Updated: February 25, 2016
·
1.028K
· marcelo

JS/PHP/RUBY Elegant switch for logical cases

Consider the following Javascript code example:

var x = 90;
if(x>100)
    alert("x > 100");
else if(x > 90)
    alert("x > 90");
else if(x > 80)
    alert("x > 80");
else if(x > 70)
    alert("x > 70");
else
    alert("x <= 70");

ugly isn't it?

Now consider the next example:

var x = 90
switch(true) {
    case x > 100:
        alert("x > 100");
        break;
    case x > 90:
        alert("x > 90");
        break;
    case x > 80:
        alert("x > 80");
        break;
    case x > 70:
        alert("x > 70");
        break;
    default:
        alert("x <= 70");
        break;
}

nicer?

Live example (Javascript):

http://jsfiddle.net/marcelow/ME9tD/

the same idea also works in other programming languages:

Ruby:

class NiceSwitchCase
  def doTheSwitch
    x = 90
    case true
      when x > 100
        puts "x > 100"
      when x > 90
        puts "x > 90"
      when x > 80
        puts "x > 80"
      else
        puts "x <= 80"
    end
   end
end

niceSwitchCase = NiceSwitchCase.new
niceSwitchCase.doTheSwitch

Live example:

http://runnable.com/me/UwJvTxExgQIsAABE

PHP:

$x = 90;
switch(true) {
    case $x > 100:
        echo "x > 100";
        break;
    case $x > 90:
        echo "x > 90";
        break;
    case $x > 80:
        echo "x > 80";
        break;
    case $x > 70:
        echo "x > 70";
        break;
    default:
        echo "x <= 70";
        break;
}

Live example:

http://runnable.com/me/UwJy7a-CsDIsAACI