当我尝试使用我定义的类方法查找实例时,我不确定为什么会收到错误。
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'。
答案 0 :(得分: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">]