AnApprentice AnApprentice - 1 year ago 72
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| %>
<% 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.



Answer Source

You could do something like{|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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download