简体   繁体   中英

Rails group and join with a comma

I'm grouping the open hours of each day with the following loop:

 <% @open_hours.group_by(&:day).each do |day, open_hours| %>
      <% if day == 1 %>
        <strong>Monday:</strong>
          <% open_hours.each do |open| %>
            <%= I18n.l open.opens, :format => :custom %> - <%= I18n.l open.closes, :format => :custom %><%= "," unless open_hours == open_hours.last %>
          <% end %>
        <% end %>
 <% end %>

This is what I get:

在此处输入图片说明

As you can see I'm trying to add a comma at the end of each array value, except for the last one:

<%= I18n.l open.opens, :format => :custom %> - <%= I18n.l open.closes, :format => :custom %><%= "," unless open_hours == open_hours.last %>

But for some reason it's not working correctly. Is there a better way to implement this???? Join the two values first with a - and then separate each opens-closes with a comma, except for the last value.

You are not comparing, what you think you are comparing:

<%= "," unless open_hours == open_hours.last %>

You are comparing the entire array open_hours to the last element of the same array open_hours.last

You probably wanted to compare the current opening time to check if it was the last element:

<%= "," unless open == open_hours.last %>

But anyway, there is a much nicer way to do this, if you have an array you can just join it together like this:

<%= open_hours.map do |open| %>
  <% I18n.l open.opens, :format => :custom %> - 
  <% I18n.l open.closes, :format => :custom %>
<% end.join(', ') %>

And probably it would be better to write some helper or some model method for this.

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