0

背景

我有一个多维散列,我想对其进行检查以确保查找找到匹配项,但它的工作方式似乎与单维散列不同。我的代码适用于找到匹配项的情况,但不适用于不匹配项。我读过一些帖子,其中在某些情况下哈希会自动为不匹配生成一个键,我认为这会导致 NIL,因为我没有专门设置一个值。我收到的不匹配案例的错误消息是:

can't convert Hash into String (TypeError)

链接到我的项目以获取上下文:https ://github.com/elvisimprsntr/siriproxy-redeye

代码摘录和源超链接:

redeyeconfig.rb

# 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"

siriproxy-redeye.rb

  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

问题

如何以不同方式定义/初始化我的哈希和/或测试不匹配?

4

1 回答 1

1

如果查找失败,您不会得到nilString返回 - 相反,您会得到一个空的Hash.

检查commandid.is_a?(Hash)commandid.empty?了解查找是否失败。

于 2012-11-08T13:35:54.073 回答