Refactor

Refactor: Ruby Array#joins for delimiting

by Irish on April 30, 2010

The other day I was reviewing a collegue’s code, who shall remain nameless to protect their innocense, and came across this lil gem:

    1 <h4>Tags</h4>
    2 <p>
    3   <% @entry.tags.each_with_index do |tag, i| %>
    4     <%= tag.name %> <% if @entry.tags.length - 1 != i %>, <% end %>
    5   <% end %>
    6 </p>

Now while it does work, it’s definately not the Ruby way, as we can rewrite it more elegantly like:

    1 <h4>Tags</h4>
    2 <p>
    3   <%= @entry.tags.join(', ') %>
    4 </p>

The ‘tags’ association here returns an array, so we can just call the join method on it. This will delimit the array contents with whatever string we like, in this case just a comma. Ah much better and concise.

{ 0 comments }