Search code examples
rubytiny-tds

ruby key not found using Modulo


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

Solution

  • 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!