【问题标题】:HAML .each function with a list and duplicatesHAML .each 具有列表和重复项的函数
【发布时间】:2019-02-04 10:14:39
【问题描述】:

我试图弄清楚如何根据 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],而不是列表中的第一个字符串,我得到了列表中每个字符串的第一个字母。

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

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

但是我该怎么做呢?

谢谢。

【问题讨论】:

    标签: html ruby list if-statement haml


    【解决方案1】:

    使用Enumerable#each_cons:

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

    【讨论】:

      【解决方案2】:

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

      @x.each do |i|
      

      这里i 是元素。所以在第一次迭代中,i 是“美国人”。因此,当您调用 i[0] 它返回字符串的第一个字符 ai[1] 返回 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
      

      返回

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

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

      希望这会有所帮助。

      【讨论】:

      • 非常感谢您的回答。真的很有帮助。 :)
      • 如何在 .each() 循环中使用 x_uniq 和 x_dup?
      猜你喜欢
      • 2015-02-25
      • 2019-02-05
      • 2022-11-30
      • 1970-01-01
      • 2018-04-12
      • 2021-01-06
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多