【问题标题】:Iterate through an array and list all but one item遍历一个数组并列出除一项之外的所有内容
【发布时间】:2014-02-09 05:03:04
【问题描述】:

我有一组要列出的项目,但我想排除一个名为“tip”的特定项目。我正在考虑类似“除非 item.name == 'tip'”之类的东西,但不确定在哪里放置类似的东西

<ul>
  <% @order.each do |item| %>
    <li><h2><%= item["quantity"] %> &times; <%= item["name"] %></h2></li>
  <% end %>
</ul>

【问题讨论】:

    标签: ruby activerecord sinatra erb


    【解决方案1】:

    unless .. end 放入&lt;% .. %&gt;

    <ul>
      <% @order.each do |item|
           unless item['name'] == 'tip' %>
        <li><h2><%= item["quantity"] %> &times; <%= item["name"] %></h2></li>
      <%   end
         end %>
    </ul>
    

    示例(为简洁起见,使用item['name'] 而不是item.name):

    require 'erb'
    
    class Listing
      def build
        @order = [
          {'quantity' => 1, 'name' => 'a'},
          {'quantity' => 2, 'name' => 'tip'},
          {'quantity' => 3, 'name' => 'c'},
        ]
    
        template = ERB.new <<-TMPL
        <ul>
          <% @order.each do |item|
               unless item['name'] == 'tip'%>
            <li><h2><%= item["quantity"] %> &times; <%= item["name"] %></h2></li>
          <%   end
             end %>
        </ul>
        TMPL
        template.result binding
      end
    end
    
    puts Listing.new.build
    

    输出:

    <ul>
    
        <li><h2>1 &times; a</h2></li>
    
        <li><h2>3 &times; c</h2></li>
    
    </ul>
    

    【讨论】:

    • 当我这样做时,我得到以下错误: (erb):10: syntax error, unexpected $end, expecting keyword_end ; _erbout.force_encoding(编码) ^
    • @Agis 我注意到双 并且只有一个,但我仍然收到同样的错误。我不太清楚为什么...
    • @csakon 您的文件中的其他地方一定有语法错误。答案的代码很好。你能把整个文件贴出来吗?
    • @Agis,你为什么删除end(没有编辑评论)?
    • @Agis 我仍然收到此错误 - {"quantity"=>1, "item"=>"The Maine Event"}:Hash 的未定义方法“名称”
    【解决方案2】:

    实现目标有很多可能性。我建议使用 next 关键字,因为它使您能够忘记后面代码中的情况,而且它不需要封闭的 end 关键字(当您在该条件下有更多代码行时,很快就会变得难以看看unless … end 子句的开始/结束位置):

    <ul>
      <% @order.each do |item|
           next if item["name"] == 'tip' %>
        <li><h2><%= item["quantity"] %> &times; <%= item["name"] %></h2></li>
      <% end %>
    </ul>
    

    【讨论】:

    • 我在尝试您的代码时收到此错误:未定义的方法 `name' for {"quantity"=>1, "item"=>"The Maine Event"}:Hash
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2023-01-05
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多