运维开发网

ruby-on-rails – 在Ruby中循环使用多个数组

运维开发网 https://www.qedev.com 2020-04-13 22:01 出处:网络 作者:运维开发网整理
我有多个ActiveRecord子类Item实例数组,我需要根据最早的事件循环打印.在这种情况下,我需要打印打印付款和维护日期如下: Item A maintenance required in 5 days Item B payment required in 6 days Item A payment required in 7 days Item B maintenance required
我有多个ActiveRecord子类Item实例数组,我需要根据最早的事件循环打印.在这种情况下,我需要打印打印付款和维护日期如下:

Item A maintenance required in 5 days

Item B payment required in 6 days

Item A payment required in 7 days

Item B maintenance required in 8 days

我目前有两个查询用于查找维护和付款项目(非独占查询)以及类似以下内容的输出:

<%- item_p = nil -%>
<%- item_m = nil -%>

<%- loop do -%>
  <% item_p ||= @items_p.shift %>
  <% item_m ||= @items_m.shift %>

  <%- if item_p.nil? and item_m.nil? then break -%>
  <%- elsif item_p and (item_m.nil? or item_p.paymt < item_m.maint) then -%>
    <%= item_p.name %> payment required in ...
  <%- elsif item_m and (item_p.nil? or item_m.maint < item_p.paymt) then -%>
    <%= item_m.name %> maintenance required in ...
  <%- end -%>
<%- end -%>

有什么方法可以清除上面(丑陋)代码的可读性?

这很快而且很脏(即没有优化):

# In your controller:
@items = @items_p.map{ |item| {:item => item, :days => item.paymt, :description => "payment"} } 
@items += @items_m.map{ |item| {:item => item, :days => item.maint, :description => "maintenance"} }
@items = @items.sort_by{ |item| item[:day] }

# In your view:
<% @items.each do |item| %>
  <%= item[:item].name %> <%= item[:description] %> required in <%= item[:days] %> days
<% end %>
0

精彩评论

暂无评论...
验证码 换一张
取 消