【问题标题】:Is there a more concise way of coding this in ruby?有没有更简洁的方式在 ruby​​ 中进行编码?
【发布时间】:2014-03-14 10:17:20
【问题描述】:

有没有更好的方法来编写这段代码?这对我来说似乎有点冗长。

我正在使用 sunspot SOLR,stored() 方法返回 nil 或值数组,如果第一个值存在,我总是想要它,或者只打印一个空字符串。

 <td><%= search_result.stored(:seo_title).first() if search_result.stored(:seo_title).present?  %></td>
  <td><%= search_result.stored(:title).first() if search_result.stored(:title).present? %></td>
  <td><%= search_result.stored(:publish_at).first() if search.result.stored(:publish_at).present? %></td>

【问题讨论】:

    标签: ruby-on-rails ruby coding-style


    【解决方案1】:
    <%- [:seo_title, :title, :publish_at].each do |key| %>
      <td><%= search_result.stored(key).try(:first) %></td>
    <% end %>
    

    无论如何,如果只有 3 个键,我宁愿继续显式渲染所有 3 个表格单元格,这里的循环具有相同的行数并且看起来不会好多少。所以另一种选择是:

    <td><%= search_result.stored(:seo_title).try(:first) %></td>
    <td><%= search_result.stored(:title).try(:first) %></td>
    <td><%= search_result.stored(:publish_at).try(:first) %></td>
    

    【讨论】:

    • 太好了,谢谢!了解 try 方法是我所缺少的。循环也很好......将同时使用......
    【解决方案2】:

    另一种选择是这样写:

    <td><%= (search_result.stored(:seo_title) || []).first %></td>
    <td><%= (search_result.stored(:title) || []).first %></td>
    <td><%= (search_result.stored(:publish_at) || []).first %></td>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 2021-07-21
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多