【问题标题】:Using an array as a hash key in Ruby在 Ruby 中使用数组作为哈希键
【发布时间】:2014-11-09 13:02:42
【问题描述】:

你好 stackers 我正在调试我的第一个 ruby​​ 应用程序,它实现了一个简单的银行(取款、存款、转账等)。我需要向用户询问他们的卡号,然后将其与哈希值进行比较以获取与该卡关联的人。尽管我似乎将相同的数组与哈希键进行比较,但我似乎无法获得该值。

def addAccount(person,card,key,account)
        @key = "Kudzu"
        if(key === @key)
            $people[card["card_number"]] = person
            $accounts[card["card_number"]] = account
            return true
        else
            puts "Access Denied: atm.addAccount"
            return false
        end
    end



    def start_trans()
        while(true)
            STDOUT.flush
            puts "Insert Card (1234 5678 9123 4567) >> "
            temp = gets.chomp
            @card = temp.split(" ")
            puts @card 
            puts @card.class
            puts $people
            @person = $people[@card]
            if(@person)
                @account = $accounts[@card]
                get_pin()
                break
            else
                puts "Didn't catch that try again" 
            end 
        end
    end

我的输出:

Insert Card (1234 5678 9123 4567) >>
6327 6944 9964 1048
6327
6944
9964
1048
Array

{[6327, 6944, 9964, 1048]=>#<Person:0x2ae5548 @zip="12345", @cash="123", @name="r", @card={"card_number"=>[6327, 6944, 9964, 1048], "exp_month"=>11, "
exp_year"=>2018, "security_code"=>468, "zip_code"=>"12345", "pin"=>"1234"}, @account=#<Account:0x2ae5530 @person=#<Person:0x2ae5548 ...>, @atm=#<Atm:0
x2ae5500>, @name="r", @balance=nil, @accounts=nil, @key="Kudzu", @pin="1234", @card={"card_number"=>[6327, 6944, 9964, 1048], "exp_month"=>11, "exp_ye
ar"=>2018, "security_code"=>468, "zip_code"=>"12345", "pin"=>"1234"}>>}

Didn't catch that try again
Insert Card (1234 5678 9123 4567) >>

为了便于阅读,我在输出之前和之后添加了一个空行。

【问题讨论】:

    标签: ruby arrays hash


    【解决方案1】:

    如果您将 $people 哈希定义为

    $people = {["6327", "6944", "9964", "1048"] => blabla... }
    

    您将获得puts $people 的以下输出:

    {["6327", "6944", "9964", "1048"] => blabla... }
    

    从您发布的输出来看,您似乎将卡号存储为$people 哈希键的数字数组。但是,您随后尝试使用 字符串数组 查询关联值,这绝对行不通。

    在查询关联数据之前,需要将输入转换为数字数组:

    puts "Insert Card (1234 5678 9123 4567) >> "
    temp = gets.chomp
    @card = temp.split(" ").map(&:to_i)
    ....
    

    一般来说,在 Ruby 中使用Array 作为哈希键是不好的做法,因为Array 它是可变的,这可能会导致键和键哈希码不一致。我会考虑使用Symbol作为卡号:

    # update people
    $people_updated = Hash[ $people.map{|k, v| [k.join.to_sym, v]} ]
    
    # query
    puts "Insert Card (1234 5678 9123 4567) >> "
    temp = gets.chomp
    @card = temp.scan(/\d+/).join.to_sym
    ...
    

    【讨论】:

    • @Ane Shaw 谢谢刚刚通过将我的输入放入散列并显示它来实现这一点(不幸的是,在发布之前我没想过尝试这个)。删除我的答案并接受你的。谢谢你真棒。
    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 2011-07-01
    • 1970-01-01
    • 2017-03-23
    • 2015-04-24
    • 1970-01-01
    • 2021-02-05
    • 2018-02-19
    相关资源
    最近更新 更多