教自己Ruby所以请耐心等待。如果我创建一个具有多个定义属性的对象并将此对象推入数组,如何在另一个方法中访问其中一个属性以在控制流方案中使用它?我正在制作银行ATM程序以获得乐趣。我的代码如下......
class Bank
class AccountMaker
attr_accessor :account_number, :name, :balance, :pin
def initialize(account_number, name, balance, pin)
@account_number = account_number
@name = name
@balance = balance
@pin = pin
end
end
def initialize
@accounts = []
end
def add_account(account_number, name, balance, pin)
account = AccountMaker.new(account_number, name, balance, pin)
@accounts << account
end
def login_screen(accounts)
def account_number_login(accounts)
puts "Please enter your 7 digit account number."
account_number_input = gets.chomp
puts accounts.instance_variable_get(:account_number)
if (/^\d{7}$/ === account_number_input) and (account_number_input === (what should go here) )
thank_you_msg()
pin_login(account_number_input)
else
error_msg()
account_number_login()
end
end
此后我有更多的代码,但它与问题无关。基本上我想从accounts数组中提取:account_number并在Login_screen函数中的if语句中使用它来查看该帐户是否确实存在。任何和所有的帮助将不胜感激。
答案 0 :(得分:2)
accounts
是一个数组。所以你必须访问它的一个元素&#39; account_number
实例变量。例如,第一个元素是:
# accounts[0] would return an instance of `AccountMaker `
accounts[0].instance_variable_get(:account_number)
此外,您不需要使用instance_variable_get
,因为您已将其声明为访问者。所以,你可以在它上面调用account_number
方法。
accounts[0].account_number