如果结果不止一行,是否可能只有一行?

时间:2019-04-16 20:58:07

标签: ruby if-statement

我有一个带有if语句的方法,如果可能的话,我想进入一行。但是,条件的一部分有两个结果-pay laterredirect_to。可以将其放在一行上吗? 我不喜欢它的语法。 (我知道如果在一行上会很长)

    def invoice
      if @invoice.reason?
        pay_later
        redirect_to admin_invoices_path, notice: t(".success_delay")
      else
        redirect_to new_admin_invoice_payment_path(@invoice)
      end
    end

2 个答案:

答案 0 :(得分:0)

好的,你可以尝试

def invoice
  @invoice.reason? ? pay_later && redirect_to(admin_invoices_path, notice: t(".success_delay")) : redirect_to(new_admin_invoice_payment_path(@invoice))
end

但是一点都不酷。并且仅在pay_later不返回假值的情况下有效

答案 1 :(得分:0)

是的,但是您可能不想这么做。

def invoice
  (pay_later; return redirect_to admin_invoices_path, notice: t(".success_delay")) if @invoice.reason?
  redirect_to new_admin_invoice_payment_path(@invoice)
end

避免将整个方法主体放在if..else块中的一种常见方法是使用保护子句:

def invoice
  return redirect_to new_admin_invoice_payment_path(@invoice) unless @invoice.reason?

  pay_later
  redirect_to admin_invoices_path, notice: t(".success_delay")
end