Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Outputting a list of items with a comma after each record excluding the last

I'm doing the following right now in one of my user mailer views:

<% @participants.each do |participant| %>
    <%=participant.user.full_name%>
<% end %>

I want a comma after every record except for the last, I suppose I could add an if block to see if the current record is the last, but that seems like a lot of code. Does rails have a better way to output a comma after every item excluding the last.

Good: XXXXX, XXXXXX, XXXXX
Bad: XXX,XXX,XXXX,

Thanks

like image 330
AnApprentice Avatar asked Feb 03 '11 22:02

AnApprentice


2 Answers

You could do something like

@participants.map{|p| p.user.full_name}.join(",")

You also may want to look into the to_sentence method that Rails adds to the Array class; it lets you do stuff like output "xxx, yyy, and zzz" automatically.

like image 65
Jacob Mattison Avatar answered Sep 25 '22 14:09

Jacob Mattison


["Apple", "Orange", "Pie"].join(", ") => "Apple, Orange, Pie"

in more complex job:

<% @participants.each do |participant| %>
  <%= participant.user.full_name %>: <%= participiant.comment %><%= "," unless participiant == @participiants.last %>
<% end %>
like image 22
fl00r Avatar answered Sep 26 '22 14:09

fl00r