【问题标题】:Accessing an object's instance variable from an array从数组中访问对象的实例变量
【发布时间】:2016-09-15 13:11:57
【问题描述】:

自学 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 语句中使用它来查看帐户是否实际存在。任何和所有的帮助将不胜感激。

【问题讨论】:

    标签: arrays ruby class object instance-variables


    【解决方案1】:

    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
    

    【讨论】:

    • 非常感谢。现在,如果我想将它与对象匹配怎么办?假设我有几个不同的对象,其帐号不同,我想要一个与用户输入的帐号匹配的对象帐户?
    • 您可能想改用Hash。帐号是键,实际帐户是值。
    • 我也这么认为。我继续把它变成一个哈希,所以和以前一样的问题只是我如何访问数组中的哈希,特别是 :account_number 值?
    • 不,我的意思是扔掉你的数组并改用哈希。 @accounts[account_number] = AccountMaker.new(account_number, name, balance, pin)。当你要查看是否有这个账号的账号时:if(@accounts[account_number_input]) ... else ...
    猜你喜欢
    • 2017-05-24
    • 2017-10-08
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多