Don P
Don P

Reputation: 63657

Dont have a comma on the last iteration of an each loop in Rails

I want to print out a list of links separated by commas in Rails.

Heres what I've got:

<%= topics.each do |topic| %>
   <a href="<%= topic.link %>" ><%= topic.name %></a>
   ,
<% end %>

Heres what I want:

<a href="thing_a">Thing A</a>, 
<a href="thing_b">Thing B</a>,
<a href="thing_c">Thing C</a>

But right now I get an extra comma on the last iteration of the loop! What should I do?

Upvotes: 9

Views: 4538

Answers (6)

user9903
user9903

Reputation:

You can do the following to print out the comma for all items except for the last:

<% topics.each do |topic| %>
  <%= topic %>
  <%= "," if topic != topics.last %>
<% end %>

This will check if the current item in the loop is the last item, and will use the <%= %> syntax to output the comma.

Upvotes: 0

Gregoire Mulliez
Gregoire Mulliez

Reputation: 1132

I made it in one line call (for active records collections) using the concat helper:

<% concat (',') if e.bills.last != b %>

concat is an ERB helper (TextHelper) to add some HTML without the <%= %> syntax, helpful to add few characters.

Here is the full code to make it clear:

<% event.bills.each do |b| %>
   <%= link_to(b.number.to_s, bill_display_path(b)) %>
   <% concat (',') if e.bills.last != b %>
<% end %>

Upvotes: 1

user3366155
user3366155

Reputation: 452

Simply try this. It works for me

<%= topics.map{|p| p.topic.name}.join(",") %>

Upvotes: 0

Raman
Raman

Reputation: 1281

if you want to do minimum possible change to your code, you can use the following

<%= topics.each do |topic| %>
  <a href="<%= topic.link %>" ><%= topic.name %></a>
     <% if(topic != topics.last) %>
     ,
     <% end %>
<% end %>

Upvotes: 5

vee
vee

Reputation: 38645

One way of doing this is with map then Array#join:

<%= topics.map { |topic| link_to(topic.name, topic.link) }.join(',').html_safe %>

Upvotes: 16

falsetru
falsetru

Reputation: 369134

How about using each_with_index, and only put comma before the content unless it's not the first item.

<% topics.each_with_index do |topic, i| %>
   <% if i > 0 %>
   ,
   <% end %>
   <a href="<%= topic.link %>"><%= topic.name %></a>
<% end %>

Upvotes: 3

Related Questions