您好堆高机我正在调试我的第一个实现简单银行(提取,存款,转账等)的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放入可读性前后,我在此处的输出中添加了空行。
如果您将$people
哈希定义为
$people = {["6327", "6944", "9964", "1048"] => blabla... }
您将获得以下输出puts $people
:
{["6327", "6944", "9964", "1048"] => blabla... }
从您发布的输出中,您似乎将卡号存储为哈希密钥的数字数组$people
。但是,您随后尝试使用string数组查询关联的值,这绝对是行不通的。
在查询关联数据之前,需要将输入转换为数字数组:
puts "Insert Card (1234 5678 9123 4567) >> "
temp = gets.chomp
@card = temp.split(" ").map(&:to_i)
....
通常,Array
在Ruby中用作哈希键是一种不好的做法,因为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
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句