Reputation: 467
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.
Upvotes: 0
Views: 269
Reputation: 4415
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.
Upvotes: 2