我正在使用Ruby创建银行帐户。即使已经定义了方法,我也会收到未定义的方法或局部变量错误,有人可以告诉我这段代码有什么问题吗?我尝试重写main_menu方法,但仍然遇到同样的错误。
class Account
attr_reader :name, :checking_account, :savings_account
def initialize(name, checking_account, savings_account)
@name = name
@checking_account = checking_account
@savings_account = savings_account
end
end
def display
puts "Enter your PIN:"
input = gets.chomp
if input = pin
main_menu
else
bad_pin
end
end
def main_menu
puts """
Welcome back #{name}!
Would you like to:
Display Balance press '1'
Make Withdrawl press '2'
Make Deposit press '3'
Exit press '4'
"""
input = gets.chomp
case option
when 1
balance
when 2
withdrawl
when 3
deposit
else
exit
end
end
def balance
puts "Which balance? Checking or Savings?"
input = gets.chomp
if input =~ /checking/i
puts "Your balance for your Checking Account is: $#{checking_account}."
elsif input =~ /savings/i
puts "Your balance for your Savings Account is: $#{savings_account}."
else
main_menu
end
end
def withdrawl(pin_number, amount)
puts "Enter PIN to make a withdrawl:"
input = gets.chomp
case withdrawl
when checking_account
@checking_account -= amount
puts "You have withdrawn $#{amount}; you now have ${checking_account} in your checking."
when savings_account
@savings_account -= amount
puts "You have withdrawn ${amount}; you now have $#{savings_account} in your savings."
else
bad_pin
end
end
def deposit
puts "Which account would you like to deposit into: Checkings, or Savings?"
input = gets.chomp
if input =~ /checking/i
@checking_account += amount
puts "You have made a deposit of $#{amount} leaving you with $#{checking_account}."
elsif input =~ /savings/i
@savings_account += amount
puts "You have made a deposit of $#{amount} leaving you with $#{savings_account}."
else
main_menu
end
end
def pin
@pin = 1234
end
def bad_pin
puts "Access Denied: incorrect PIN"
exit
end
my_account = Account.new("Thomas", 500_000, 750_000)
display
我收到的错误是:
bank.rb:25:in `main_menu': undefined local variable or method `name' for main:Object (NameError)
from bank.rb:16:in `display'
from bank.rb:101:in `<main>'
答案 0 :(得分:1)
您必须将所有这些方法放入Account
类主体中。否则,他们将看不到实例变量或attr_reader
方法。
class Account
attr_reader :name, :checking_account, :savings_account
def initialize(name, checking_account, savings_account)
@name = name
@checking_account = checking_account
@savings_account = savings_account
end
end # <---- This closes your class, it has to be moved past the last method
通过适当的缩进立即可以看到此错误。
最后,您拨打display
的{{1}}:
my_account
答案 1 :(得分:1)
移动类
中的所有方法并在类的实例上调用您的显示方法,即在您的情况下调用my_account
这应该可以做到! :)