在Ruby中使用数组作为哈希键

时间:2014-11-09 04:21:09

标签: ruby arrays hash

Hello 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) >>

为了便于阅读,我在放置$ people之前和之后在我的输出中添加了一个空行。

1 个答案:

答案 0 :(得分:0)

如果您将$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
...