ruby key not found using Modulo

2019-08-31 02:08发布

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"=>""}

标签: ruby tiny-tds
1条回答
神经病院院长
2楼-- · 2019-08-31 02:20

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!

查看更多
登录 后发表回答