BACKGROUND
I have a multidimensional hash which I want to perform a check to ensure that the lookup found a match, but it does not seem to work the same as single dimension hash. My code works for a case where it finds a match, but not for a non-match. I have read posts in which under certain circumstances the hash will automatically generate a key for a non match, which I think will result in a NIL since I did not specifically set a value. The error message I get for a non-match case is:
can't convert Hash into String (TypeError)
Link to my project for context: https://github.com/elvisimprsntr/siriproxy-redeye
Excerpt of code and hyperlinks to source:
# Channel number and command syntax to actual RedEye device commandIds
# Note: Must all be lower case. Use multiple entries for variability in Siri response.
@cmdId = Hash.new(&(p=lambda{|h,k| h[k] = Hash.new(&p)}))
@cmdId["all"]["cable box"]["0"] = "/commands/send?commandId=3"
@cmdId["all"]["cable box"]["zero"] = "/commands/send?commandId=3"
@cmdId["all"]["cable box"]["1"] = "/commands/send?commandId=4"
def send_command(command)
commandid = @cmdId[@reRoom][@reDevice][command.downcase.strip]
unless commandid.nil?
say "OK. Sending command #{command}."
# FIXIT: Does not properly handle no match. Results in "can't convert Hash into String (TypeError)"
# This may be due to the fact that dynamically created multidimensional hash will create new keys if a match is not found which will pass the NIL check.
Rest.get(@reIp[@reSel] + @roomId[@reRoom] + @deviceId[@reRoom][@reDevice] + commandid)
else
say "Sorry, I am not programmed for command #{command}."
end
request_completed
end
QUESTION
How do I define/initialize my hash differently and/or test for a non-match?
You don’t get
nilor aStringback in case of a failed lookup – instead you get an emptyHash.Check if
commandid.is_a?(Hash)andcommandid.empty?to know if the lookup failed or not.