访问和检查哈希值

时间:2016-05-25 02:36:18

标签: ruby hash

环顾四周,无法找到我正面临的问题的正确答案。我想访问并检查哈希值中的值。代码如下......

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

    attr_accessor :int_account_number, :int_account_pin

    def initialize
        @accounts = {}
        @int_account_number = int_account_number
        @int_account_pin = int_account_pin
    end

    def add_account(account_number, name, balance, pin)
        @accounts[account_number] = AccountMaker.new(account_number, name, balance, pin)
    end

    def login_screen

        def account_number_login
            puts "Please enter your 7 digit account number."
            account_number = gets.chomp
            int_account_number = account_number.to_i

            if @accounts.has_key?(int_account_number) and (/^\w{7}$/ === account_number)
                thank_you_msg()
                pin_login(int_account_number)
            else
                error_msg()
                account_number_login()
            end
        end

        def pin_login(int_account_number)
            puts "Please enter your 4 digit pin."
            account_pin = gets.chomp
            int_account_pin = account_pin.to_i #May have to use this later

            #puts int_account_number, int_account_pin #Used to check if variables come through

            if (What Should go here?) == int_account_pin #(/^\d{4}$/ === account_pin) 
                thank_you_msg
                main_menu()
            else
                error_msg()
                pin_login(int_account_number)
            end
        end

        account_number_login()
    end

    def main_menu    
    end

end

我遇到的问题是如何为用户输入的帐号(密钥)访问pin的哈希值,并检查它是否与用户条目匹配?哈希包含:pin下的值,但我最难尝试访问并进行比较。

1 个答案:

答案 0 :(得分:1)

  

我的问题是如何访问针脚的哈希值   用户输入帐号(密钥)并检查其是否与用户匹配   条目?哈希包含下面的值:pin但是我有   最难以尝试访问并进行比较。

像这样:

@accounts[int_account_number].pin

片段:

@accounts[int_account_number]

是一个AccountMaker实例。并且,AccountMaker实例具有名为pin()的getter方法(以及名为pin=()的setter方法):

                                          Declared right there!
                                                   |
class AccountMaker                                 V
  attr_accessor :account_number, :name, :balance, :pin  

但是,你的代码需要重新组织 - 从缩进开始:ruby indenting是2个空格 - 不是1个空格,不是4个空格。如果你愿意,你可以缩进ruby代码7个空格 - 但是当你在公共论坛上发帖时,不要指望任何人帮助你。因此,您的第一个任务是将所有代码重新缩进为2个空格。

接下来,摆脱嵌套类:将其移至顶层并将其重命名为Account。类名不是动词 - 它们是名词。方法是动词。

然后,摆脱所有嵌套的def - 嵌套def很可能不会像你认为的那样工作。相反,所有def都应该在Bank类的顶层定义。