How to write case statement into views – Rails quick tips

Case statement in a view – Fail!

Well I can’t recall when (and why) but one time I was writing a view in a Rails project and needed to write a case statement (of course I could have done it with usual if / else /elsif statement, but the case statement seemed more natural). My first try (and I remember I was pretty confident that this was the way to go) had gone like this:

# my_view.html.erb

<% case params[:animal] %>
<% when "dog" %>
<p>Barf!</p>
<% when "cat" %>
<p>Meow!</p>
<% end %>

Then the pretty sweet compile error page came screaming at me.

Case statement in a view – Success!

A few minutes later I have found out that the right syntax to write a case statement in a view is:

# my_view.html.erb

<% case params[:animal] 
   when "dog" %>
<p>Barf!</p>
<% when "cat" %>
<p>Meow!</p>
<% end %>

Hope I helped with this quick little tip!

2 Comments How to write case statement into views – Rails quick tips

Leave a Reply to Sergio Cancel reply

Your email address will not be published. Required fields are marked *


*