Say I have a collection of objects in product.categories
.
What I would like to happen is for my list of categories to be printed out like:
Men, Women
If I do:
<% product.categories.each do |cat| %>
<% if product.categories.count > 1 %>
<%= "#{cat.name}, " %>
<% else %>
<%= "#{cat.name} " %>
<% end %>
<% end %>
That prints Men, Women,
.
So without adding a billion rules to check for last element and all this stuff, how do I handle the following cases:
,
,
at the end. .
<-- This is a nice-to-have but not a must have. How do I handle this?
Thanks.
<%= product.categories.map{|cat| cat.name}.join(', ').to_s + "." %>
Try above, that will work. Do let me know if you want any else.
You can do:
<%= product.categories.collect{|c| c.name} * ', ' %>.
The "asterisk" method ( Array#*
) is an alias for Array#join
.
Note the period just outside the ERb tag.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.