Ruby初始化奇怪的参数性能

时间:2015-11-11 15:43:35

标签: ruby class initialization

我有一个非常奇怪的问题。 如果我们运行此类,则由于binding.pry而在方法调用中执行将被中断。

如果我们按预期检查receiver方法的值为Ivo。但是`sender的值是这个对象,基本上是params的数组。

["Gerard",
 "Ivo",
 #<Bank:0x007fb4339ac2b8
  @accounts=
   [#<Account:0x007fb4339ac240 @bank=#<Bank:0x007fb4339ac2b8 ...>, @founds=0, @user="Gerard">,
    #<Account:0x007fb4339ac1f0 @bank=#<Bank:0x007fb4339ac2b8 ...>, @founds=0, @user="Ivo">]>,
 #<Bank:0x007fb4339ac2b8
  @accounts=
   [#<Account:0x007fb4339ac240 @bank=#<Bank:0x007fb4339ac2b8 ...>, @founds=0, @user="Gerard">,
    #<Account:0x007fb4339ac1f0 @bank=#<Bank:0x007fb4339ac2b8 ...>, @founds=0, @user="Ivo">]>,
 1200]

这是整个班级。有什么解释吗?

require_relative './lib/bank'

class TransferAgent
  def initialize(sender, receiver, sender_bank, receiver_bank, amount)
    @sender        = sender,
    @receiver      = receiver,
    @sender_bank   = sender_bank,
    @receiver_bank = receiver_bank,
    @amount        = amount
  end

  def call
    binding.pry
    transfer_result = perform_transfer until transfer_result.succed?
  end

  private

  attr_reader :sender, :receiver, :amount, :sender_bank, :receiver_bank

  def perform_transfer
    sender_account.transfer_money(receiver_account, amount)
  end

  def sender_account
    @sender_account ||= sender_bank.account sender
  end

  def receiver_account
    @receiver_account ||= receiver_bank.account receiver
  end
end

bank_a = Bank.new

bank_a.create_account("Gerard")
bank_a.create_account("Ivo")

TransferAgent.new("Gerard", "Ivo", bank_a, bank_a, 1200).call

1 个答案:

答案 0 :(得分:2)

在初始化程序中,删除尾随逗号。整个初始化程序将被解析为单个并行赋值。

快速演示正在发生的事情:

f