DEV Community

Arnold Ho
Arnold Ho

Posted on

Ruby If-else and Case-when statements Explained

Disclaimer: I am learning in public so please do correct me if I get something wrong

In some modern programming languages such as Javascript and Ruby, there are different ways of writing loops that will do specific things under different conditions. Two most common form of this are the if statements and the switch statements. These are not exactly the same but act quite similarly. Depend on the situation you might favour one over the other.

I am going to explain both using the same example. The example will be in Ruby since that's the language I'm learning.

We want to define a statement that returns what someone should wear under different temperatures (in Celsius):

An if statement will look something like this:

if weather > 30
  puts "Heat wave, stay indoor"
elsif weather (<= 30 && > 20)
  puts "shorts, T-shirt, sunglasses"
elsif weather (<= 20 && > 10)
  puts "jumper and long trousers"
else
  puts "wear a thick jacket"
end
Enter fullscreen mode Exit fullscreen mode

Whereas a switch statement in Ruby looks like this:

case weather
when > 30
  puts "Heat wave, stay indoor"
when 21..30
  puts "shorts, T-shirt, sunglasses"
when 11..20
  puts "jumper and long trousers"
else
  puts "wear a thick jacket
end
Enter fullscreen mode Exit fullscreen mode

In an if statement, anything can be the condition, it doesn't necessarily have to be the weather like we've defined above, for example, we can take an extra argument like this:

if weather > 30
  puts "Heat wave, stay indoor"
if weather > 30 && work_from_home == false
  puts "short sleeve and loads of sunscreen"
elsif weather (<= 30 && > 20)
  puts "shorts, T-shirt, sunglasses"
elsif weather (<= 20 && > 10)
  puts "jumper and long trousers"
else
  puts "wear a thick jacket"
end
Enter fullscreen mode Exit fullscreen mode

here we added an additional argument called work_from_home that gives a true or false output if we are working from home or not. An if statement can handle configurations like this.

However, a switch statement takes the output of the case argument and see which switch condition it satisfies. So it is very useful if all the conditions are only dependent on one variable. In some cases, writing a switch statement can make your code cleaner if you have only one variable your statement depends on.

I hope you find this useful. Have a nice day!

Happy coding!

Top comments (0)