Hacking a nil object / Workaround

Posted on February 6, 2009, under Rails.

I was looking for a way to workaround a nil object. For instance if @project.name is nil, I wanted to display as “N/A” and otherwise the project name (@project.name)

Normal Way

<% unless @project.nil? %>
  <%=  @project.name %>
<% else %>
  <%=  "N/A" %>
<% end  %>

Another Way

<%= @project.name rescue nil || "N/A" %>

Just in a one single line!, Neat ah :-)

Hope this helps!

Leave a Comment

You must be logged in to post a comment.