2014-01-26 64 views
0

我不確定爲什麼我在嘗試使用我定義的類方法查找實例時收到錯誤。創建類方法

bank_account.rb

class BankAccount 
    attr_reader :balance 

    def self.create_for(first_name, last_name) 
     @accounts ||= [] 
     @accounts << BankAccount.new(first_name, last_name) 
    end 

    def self.find_for(first_name, last_name) 
     @accounts.find{|account| account.full_name == "#{first_name} #{last_name}"} 
    end 

    def initialize(first_name, last_name) 
     @balance = 0 
     @first_name = first_name 
     @last_name = last_name 
    end 

    def full_name 
     "#{first_name} #{@last_name}" 
    end 

    def deposit(amount) 
     @balance += amount 
    end 

    def withdraw(amount) 
     @balance -= amount 
    end 

end 

在IRB中,我創建使用create_for類方法兩個銀行賬戶。

$BankAccount.create_for("Brad", "Pitt") 
$BankAccount.create_for("Angelina", "Jolie") 

當我試圖找到實例,

$BankAccount.find_for("Angelina", "Joile") 

我收到此錯誤:

NameError: undefined local variable or method `first_name' for #<BankAccount:0x007fb914a47700> 

我不知道爲什麼它說, 'FIRST_NAME' 沒有定義。

回答

1

以下部分

def full_name 
    "#{first_name} #{@last_name}" # <~~ here you missed @ symbol before first_name 
end 

需求是

def full_name 
    "#{@first_name} #{@last_name}" 
end 

全碼:

class BankAccount 
    attr_reader :balance 

    def self.create_for(first_name, last_name) 
     @accounts ||= [] 
     @accounts << BankAccount.new(first_name, last_name) 
    end 

    def self.find_for(first_name, last_name) 
     @accounts.find{|account| account.full_name == "#{first_name} #{last_name}"} 
    end 

    def initialize(first_name, last_name) 
     @balance = 0 
     @first_name = first_name 
     @last_name = last_name 
    end 

    def full_name 
     "#{@first_name} #{@last_name}" 
    end 

    def deposit(amount) 
     @balance += amount 
    end 

    def withdraw(amount) 
     @balance -= amount 
    end 
    def self.account_holders;@accounts;end 

end 
BankAccount.create_for("Brad", "Pitt") 
BankAccount.create_for("Angelina", "Jolie") 
BankAccount.find_for("Angelina", "Jolie") 
# => #<BankAccount:0x99de7d0 
#  @balance=0, 
#  @first_name="Angelina", 
#  @last_name="Jolie"> 

BankAccount.account_holders 
# => [#<BankAccount:0x99de8d4 
#  @balance=0, 
#  @first_name="Brad", 
#  @last_name="Pitt">, 
#  #<BankAccount:0x99de7d0 
#  @balance=0, 
#  @first_name="Angelina", 
#  @last_name="Jolie">] 
+1

謝謝!我應該仔細檢查!我將在6分鐘內接受答案 – wag0325

+0

您是否碰巧知道如何顯示我爲BankAccount創建的所有對象?我是否需要爲此創建一個方法?我嘗試過BankAccount.all,但我沒有收到任何東西。 – wag0325

+1

@ wag0325只需添加一個像'def self.account_holders; @accounts; end'的方法。然後將其稱爲「BankAccount.account_holders」。而已。 –