如何仅索引符合特定条件的集合项?

Posted

技术标签:

【中文标题】如何仅索引符合特定条件的集合项?【英文标题】:How to only index collection items that match specific condition? 【发布时间】:2021-12-08 21:09:24 【问题描述】:

在我的项目中,我想索引数据。

视图代码:

- @phones.each.with_index(1) do |(phone,no_of_duplicate),index|
  .row.py-2
     .col-2 = index
    - if no_of_duplicate.count > 1      
     .col-3 = phone
     .col-3 = no_of_duplicate.count
     .col-4 .......................................
        
  

我得到的结果是 如果我将视图上的代码更改为:

- @phones.each.with_index(1) do |(phone,no_of_duplicate),index|
 - if no_of_duplicate.count > 1
  .row.py-2
    .col-2 = index
    .col-3 = phone
    .col-3 = no_of_duplicate.count

得到的结果为:

我该如何解决这个问题?

【问题讨论】:

【参考方案1】:

您可以在分配索引和渲染之前filter

@phones.filter  |(_,no_of_duplicate)| no_of_duplicate.count > 1 .each <...>

【讨论】:

以上是关于如何仅索引符合特定条件的集合项?的主要内容,如果未能解决你的问题,请参考以下文章