【发布时间】:2016-04-02 07:44:18
【问题描述】:
我有一个 yaml 序列,其中包含我想在某些地方完整循环但在其他地方只部分循环的推荐。简而言之,如何在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]。在我的天真中,我认为这类似于在循环之外选择特定的序列项,例如。 %p= data.testimonials[0].name,像这样:
- data.testimonials[0, 4, 7].each do |testimonial|
%div
%img{ :src => testimonial.photo }
%p= testimonial.name
%p= testimonial.quote
但是...这会返回 “参数数量错误” 错误,因为该方法似乎只接受序列/数组中的单个范围,例如 testimonials[4, 7](或 [4..7] ,2..2 等)。
问题
有没有办法将多个范围传递到这个循环中,例如。 [0..2 && 4..7](这不起作用,但你明白我的意思)?或者,这甚至是实现这一结果的推荐方式吗?也就是说,是否有一种标准且更有效的方法来选择和循环 yaml 序列中的特定项目(或范围)?
注意
我感觉select方法in this post(贴在下面)包含了答案...但我可能是错的,我不知道如何使用它...
选择
(要避免的别名:find_all)
当您需要过滤(即“选择”)多个值时非常有用。[1, 2, 3, 4].select { |e| e % 2 == 0 } # returns [2, 4]
为了测试,我尝试将上面的内容翻译成- data.testimonials.select do |testimonial| testimonial == 1,它只返回整个序列,以及- data.testimonial.select {|testimonial| testimonial == 1},它返回一个语法错误......
【问题讨论】: