Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 336
Don P Avatar asked Nov 02 '14 03:11

Don P


1 Answers

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

<%= topics.map { |topic| link_to(topic.name, topic.link) }.join(',').html_safe %>
like image 104
vee Avatar answered Oct 13 '22 10:10

vee