【问题标题】:Concat Integer & String to form a methodConcat Integer 和 String 组成一个方法
【发布时间】:2016-01-14 13:40:32
【问题描述】:

我有点怀疑这是否可能,但我想我会尝试看看社区是否可以帮助我想出一个解决方案。

在我的应用程序中,用户可以创建发票,我试图让他们从表单中设置定期发票,以便他们可以选择数字、间隔(年、月、日),然后我将能够得到一个间隔。

理想情况下它应该是这样的:1.year.from_now

这会给我发送下一张发票的日期。这是一个内置的 rails helper,我想使用我的数据库中的信息来形成它

因此,在 Invoice.create 上,我检查它是否是将转换为模板 (Recurringinvoice) 的经常性发票,如果是,我将创建它:

    Recurringinvoice.create(customer_id: @customer.id, company_id: @company.id, 
invoice_number: @invoice.invoice_number, private_notes: @invoice.private_notes, 
customer_notes: @invoice.customer_notes, payment_terms: @invoice.payment_terms, 
status: "unpaid", discount: @invoice.discount, po_number: @invoice.po_number, 
interval: @invoice.interval, 
invoice_interval_number: @invoice.invoice_interval_number)

我想做的事:@invoice.invoice_interval_number + "." + @invoice.interval + ".from_now"

这将给我 1.year.from_now 或 2.days.from_now 等。

无论如何我可以做到这一点吗?有没有更好的解决方案我没有想到?

【问题讨论】:

    标签: string ruby-on-rails-4 integer concatenation


    【解决方案1】:

    在 ruby​​ 中,您可以使用 send 方法通过名称调用方法。

    • @invoice.invoice_interval_number 是一个整数。
    • @invoice.interval 包含您要在 Integer 上调用的方法的名称。
    • from_now 是您要在前一个方法的结果上调用的方法。

    这给了我们:

    @invoice.invoice_interval_number.send(@invoice.interval).from_now
    

    文档:http://ruby-doc.org/core-2.2.3/Object.html#method-i-send

    【讨论】:

    • 美丽。它工作得很好,我从来不知道。
    • 这是 Ruby 元编程可能性的一部分。太棒了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    相关资源
    最近更新 更多