Passionate Development From Journeyman to Master

Know Your Switch Statement? Think Again

I was reading Humble Little Ruby Book the other day and got up to Hustle and Flow chapter - a chapter dedicated to loops, conditions and the usual suspect.

I read something really interesting about the way switch statement in Ruby works - it does not fall through. What does fall through mean?

[coldfusion] switch x: case 1: print 1; break; case 2: print 2; break; case 3: print 3; case 4: print 4; break; end [/coldfusion]

In the code above if you set x = 3 you’ll get 3 and 4 printed out - that’s because the case checking for 3 falls through without the break keyword. Only by using the break - the fall through is stopped.

In Ruby, you do not need to put the word break for each cases - as the switch statement in Ruby does not fall through.

I was quite shocked - I thought this fall through behavior is standard for all languages. I was wrong and looking at Switch Statement at Wikipedia - Ruby is not the only language that doesn’t allow fall through, Ada, Eiffel are also languages that don’t support this.