Search code examples
arraysrubyclassobjectinstance-variables

Accessing an object's instance variable from an array


Teaching myself Ruby so please bear with me. If I create an object with several defining attributes and push this object into an array how do I access one of those attributes in another method to use it in a control flow scheme? I'm making a banking ATM program for fun. My code is below...

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

I have more code after this but its not pertinent to the question. Essentially I want to extract from the accounts array :account_number and use it in the if statement within the Login_screen function to see if the account actually exists. Any and all help would be appreciated.


Solution

  • accounts is an array. So you have to access one of its elements' account_number instance variable. For example the first element's:

    # accounts[0] would return an instance of `AccountMaker `
    accounts[0].instance_variable_get(:account_number)
    

    Also, you don't need to use instance_variable_get, since you already declared it as accessor. So, you can just call account_number method on it.

    accounts[0].account_number