AnApprentice AnApprentice - 4 months ago 17
Ruby Question

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

Answer

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.