从数组访问对象的实例变量

Accessing an object's instance variable from an array

自学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

此后我还有更多代码,但与问题无关。本质上,我想从帐户数组中提取 :account_number 并在 Login_screen 函数内的 if 语句中使用它来查看该帐户是否实际存在。任何帮助将不胜感激。

accounts 是一个数组。因此,您必须访问其中一个元素的 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