HAML .each 带有列表和重复项的函数

HAML .each function with a list and duplicates

我想知道如何根据 if 语句分配列表的特定元素。

这是列表:

@x = ["american", "assistive", "audio", "blind", "braille", "closed-captioning", "closed-captioning", "deaf", "low", "phone", "question-circle", "question-circle", "sign", "tty", "universal", "wheelchair"]

这是我的 haml 代码:

        %ul.list-inline
        - @x.each do |i|
          - if i[0].length < i[1].length
            %li            
              %i{:class=>"fas fa-#{i[0]} fa-2x"}
              %span.f6 #{i[0]}                      
          - else
            %li             
              %i{:class=>"far fa-#{i[1]} fa-2x"}
              %span.f6 #{i[1]} 

我想做的是确定列表中每个字符串的长度,并将其与列表中下一个字符串的长度进行比较。

一旦第二个字符串被确定为重复的,它应该在 else 语句下。

我面临的问题是,通过使用 i[0],而不是列表中的第一个字符串,我得到了列表中每个字符串的第一个字母。

我不知道我使用长度的方式是否是解决这个问题的最佳方式,所以如果其他人有更好的解决方案,我愿意接受,只要它能完成工作。

我在想,也许如果我可以根据哪些元素是唯一的,哪些是重复的来过滤列表中的元素,然后我就可以相应地分配它们。

但是我该怎么做呢?

谢谢。

使用Enumerable#each_cons:

- @x.each_cons(2) do |cur, nxt|
  - if cur.length < nxt.to_s.length
    ...
  - else
    ...

要回答您问题的第一部分,其中 i[0]i[1] 返回单个字母而不是元素,让我们检查您的代码:

@x.each do |i|

这里i是元素。所以在第一次迭代中,i 是 'american'。因此,当您调用 i[0] 时,它会 returns 字符串的第一个字符,即 ai[1] returns m 两个长度都是1.

相反,您应该像这样修改代码:

%ul.list-inline
        - @x.each_cons(2) do |current, next|
          - if current.length < next.length
            %li            
              %i{:class=>"fas fa-#{current} fa-2x"}
              %span.f6 #{current}                      
          - else
            %li             
              %i{:class=>"far fa-#{next} fa-2x"}
              %span.f6 #{next} 

关于你问题的第二部分,你将@x定义为:

@x = ["american", "assistive", "audio", "blind", "braille", "closed-captioning", "closed-captioning", "deaf", "low", "phone", "question-circle", "question-circle", "sign", "tty", "universal", "wheelchair"]

获取唯一元素:

@x_uniq = @x.uniq

要获取重复项:

@x_dup = @x.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }.select{ |k,v| v > 1 }.keys

哪个returns

["closed-captioning", "question-circle"]

在我看来,使用第二种方法过滤数据并使用它是比比较元素及其长度更好的解决方案。

希望对您有所帮助。