gpt4 book ai didi

ruby-on-rails - 在 Ruby 中循环遍历多个数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:13:56 26 4
gpt4 key购买 nike

我有多个 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

我目前有两个查询,用于查找maintenancepayment 项目(非排他性查询),并输出如下内容:

<%- 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 -%>

有什么方法可以改善上述(丑陋的)代码的可读性?

最佳答案

拥抱鸭子类型并确保您的对象是多态。您希望您的付款项目与维护项目可比较,以便对它们进行分类。

所以,假设你有一个 Payment和一个 Maintenance类:

module Due
include Comparable

# Compare this object with another. Used for sorting.
def <=>(other)
self.due <=> other.due
end
end

class Payment < ActiveRecord::Base
include Due

alias_method :due, :payment

def action
"#{name} requires payment"
end
end

class Maintenance < ActiveRecord::Base
include Due

alias_method :due, :maintenance

def action
"#{name} requires maintenance"
end
end

看看我们如何创建 action , due<=> 两个类中的方法?我们还注意包含 Ruby 内置模块 Comparable .这使我们能够执行以下操作:

# Assuming 'payment' and 'maintenance' are date fields...
a = Payment.new :payment => 3.days.from_now
b = Maintenance.new :maintenance => 2.days.from_now
[a, b].sort
#=> [b, a]

然后 View 变得很简单:

<% (@payment_items + @maintenance_items).sort.each do |item| %>
<%= item.action %> in <%= distance_of_time_in_words_to_now(item.due) %><br/>
<% end %>

我确定我没有正确了解您的实现细节,但我希望这能让您了解如何解决您的问题。

关于ruby-on-rails - 在 Ruby 中循环遍历多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6271238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com