ruby key not found using Modulo

别说谁变了你拦得住时间么 提交于 2019-12-12 05:56:51

问题


I am trying to use the string's modulo function % to take a hash and inject it's values into the appropriate places inside of a string but I always receive key{x} not found (KeyError) even though I can confirm that the key is there. What am I doing wrong?

s = "Invalid: %{totalInvalid} , OutofThreshold: %{totalOutOfThreshold} "
puts row.fetch ('totalInvalid') #<-Just checking to make sure the key is in there
ext = s % row

I get this output:

0 #<- Key does seem to be in there, returns correct value
in `%': key{totalInvalid} not found (KeyError)

The hash is being provided from tiny tds (hitting an SQL server) and when puts is used on it:

{"environment"=>"prd       ", "locale"=>"uk        ", "totalProducts"=>666, "to
talOutOfThreshold"=>0, "totalInvalid"=>0, "epochtime"=>1444444444, "thresholdPro
ductIds"=>"", "invalidProductIds"=>""}

回答1:


In here, the hash keys should be symbols instead of strings, so try the following:

to_inject = row.each_with_object({}) { |(key, value), h| h[key.to_sym] = value  }
s = "Invalid: %{totalInvalid} , OutofThreshold: %{totalOutOfThreshold} "
ext = s % to_inject

This should help!



来源:https://stackoverflow.com/questions/28964629/ruby-key-not-found-using-modulo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!