使用Modulo找不到ruby密钥
我正在尝试使用字符串的模数函数%
来获取哈希并将其值注入字符串内的适当位置但是我总是收到key{x} not found (KeyError)
即使我可以确认密钥在那里。 我究竟做错了什么?
s = "Invalid: %{totalInvalid} , OutofThreshold: %{totalOutOfThreshold} " puts row.fetch ('totalInvalid') #<-Just checking to make sure the key is in there ext = s % row
我得到这个输出:
0 #<- Key does seem to be in there, returns correct value in `%': key{totalInvalid} not found (KeyError)
哈希是从微小的tds(命中SQL服务器)提供的,当使用puts时:
{"environment"=>"prd ", "locale"=>"uk ", "totalProducts"=>666, "to talOutOfThreshold"=>0, "totalInvalid"=>0, "epochtime"=>1444444444, "thresholdPro ductIds"=>"", "invalidProductIds"=>""}
在这里,散列键应该是符号而不是字符串,因此请尝试以下操作:
to_inject = row.each_with_object({}) { |(key, value), h| h[key.to_sym] = value } s = "Invalid: %{totalInvalid} , OutofThreshold: %{totalOutOfThreshold} " ext = s % to_inject
这应该有帮助!