简体   繁体   中英

How do I add commas to the display of collection items if a collection has multiple products intelligently?

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:

  1. If there is one object, put no ,
  2. If this is the last of multiple objects, don't put a , at the end.
  3. If this is the last object, in a collection of many, end with a . <-- 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM