如何使用 haml 遍历 yaml 序列中的选定项目

How to loop through selected items in yaml sequence using haml

我有一个包含推荐的 yaml 序列,我想在某些地方完整地循环,但在其他地方只循环部分。简而言之,select 如何在 haml 中循环遍历 yaml 序列中的特定项目?

下面的示例被剥离

我的 yaml 数据

# testimonials.yml

-
  name: 'Jill'
  quote: 'An unbelievable experience!'
  photo: 'jill.jpg'
-
  name: 'Jack'
  quote: 'I unreservedly recommend this programme'
  photo: 'jack.jpg'
-
  # ... etc 

一个基本的工作 haml 循环

-# about.html.haml

- data.testimonials.each do |testimonial|
  %div
    %img{ :src => testimonial.photo }
    %p= testimonial.name
    %p= testimonial.quote

我想要实现的目标

然而,在另一部分中,我只想循环浏览序列中的特定推荐,例如。 [0, 4, 7]。出于天真,我假设这类似于 selecting 循环外的特定序列项,例如。 %p= data.testimonials[0].name,像这样:

- data.testimonials[0, 4, 7].each do |testimonial|
  %div
    %img{ :src => testimonial.photo }
    %p= testimonial.name
    %p= testimonial.quote

但是......这个returns一个'wrong number of arguments'错误,因为看起来这个方法只接受序列/数组中的一个范围,例如testimonials[4, 7](或[4..7]2..2等)。

问题

有没有办法将多个范围传递到这个循环中,例如。 [0..2 && 4..7](这不起作用,但你明白我的意思)?或者,这甚至是实现此结果的推荐方法吗?也就是说,是否有一种标准且更有效的方法来 select 循环遍历 yaml 序列中的特定项目(或范围)?

注意

我觉得select方法in this post(粘贴在下面)包含答案...但我可能错了,我不知道如何使用它...

select
(alias to avoid: find_all)
Very useful when you need to filter (i.e. “select”) multiple values.
[1, 2, 3, 4].select { |e| e % 2 == 0 } # returns [2, 4]

为了测试,我尝试将上面的内容翻译成 - data.testimonials.select do |testimonial| testimonial == 1,这只是 returns 整个序列,以及 - data.testimonial.select {|testimonial| testimonial == 1},returns语法错误...

使用each_with_index

- data.testimonials.each_with_index do |testimonial, index|
  - if [0, 4, 7].include? index
    %div
      %img{ :src => testimonial.photo }
      %p= testimonial.name
      %p= testimonial.quote

您可以使用 Array#values_at,它将提取给定索引号的值并仅循环这些值,而不是循环遍历所有元素。 例如:

> array = ["a", "b", "c", "d", "e", "f", "g", "h"] 
> array.values_at(0, 4, 7)
#=> ["a", "e", "h"]

使用 each_with_index 传递元素及其索引,然后在块中执行 if [2, 6, 9].include?要检查的索引

你也可以用这个Array#values_at

例如

- data.testimonials.values_at(0, 4, 7).each do |testimonial|
  %div
    %img{ :src => "#{testimonial.photo}" }
    %p= testimonial.name
    %p= testimonial.quote