Rails小组并加入逗号

时间:2019-07-03 08:30:47

标签: ruby-on-rails

我通过以下循环将每天的开放时间分组:

 <% @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 %>

这就是我得到的:

enter image description here

您可以看到,我试图在每个数组值的末尾添加一个逗号,除了最后一个:

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

但是由于某种原因,它无法正常工作。有没有更好的方法来实现呢????首先用-将两个值连接起来,然后用逗号分隔每个开-关,最后一个值除外。

1 个答案:

答案 0 :(得分:2)

您不比较,您认为自己在比较:

# I get only one definition and update him, not iterate all my definitions
$definition = Invoke-RestMethod -Uri $url -Method Get

# Change the branch trigger from "test" to "master"
$definition.triggers[0].branchFilters[0] = "+refs/heads/master"

# Add another branch trigger - "feature/*"
$definition.triggers[0].branchFilters[0] += "+refs/heads/feature/*"

$body = $definition | ConvertTo-Json -Depth 10
Write-Host $body

Invoke-RestMethod -Uri $url -Method Put -ContentType application/json -Body $body

您正在将整个数组<%= "," unless open_hours == open_hours.last %> 与同一数组open_hours的最后一个元素进行比较

您可能想比较当前的开放时间以检查是否是最后一个元素:

open_hours.last

但是无论如何,有一种更好的方法来执行此操作,如果您有一个数组,可以像这样将其连接在一起

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

为此可能需要编写一些帮助程序或一些模型方法。

相关问题