2012-11-08 5 views
0

배경루비 : 테스트 다차원 해시

내가 조회가 일치하는 항목을 찾을 수 있도록하기 위해 검사를 수행 할 다차원 해시를 가지고 있지만, 단일 차원 해시와 동일하게 작동하지 않습니다. 내 코드는 일치하는 항목을 찾지 만 일치하지 않는 항목은 찾지 않습니다. 특정 상황에서 해시가 자동으로 일치하지 않는 키를 생성하는 게시물을 읽었습니다. 특정 키를 설정하지 않았기 때문에 NIL이 발생한다고 생각합니다. '비 일치하는 경우에 얻을 오류 메시지는 다음과 같습니다 컨텍스트 내 프로젝트에

can't convert Hash into String (TypeError) 

링크 :

redeyeconfig.rb : 소스 코드와 하이퍼 링크의 https://github.com/elvisimprsntr/siriproxy-redeye

발췌

# 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 

질문

어떻게/비 일치 다르게 및/또는 테스트 내 해시를 초기화 정의합니까?

답변

1

룩업에 실패한 경우 nil 또는 String이 표시되지 않으며 대신 Hash이 비어 있습니다.

commandid.is_a?(Hash)commandid.empty?을 확인하여 조회가 실패했는지 여부를 확인하십시오.

+0

아하 .. 당신은 항상 해시를 얻고 있기 때문에 안전하게 타입 체크를 할 수 있습니다 :) – doesterr

+0

굉장! 나는 commandid.empty가 아닌 한'을 사용 했습니까? 아니면 둘 다 확인해야합니까? – Elvis

+0

LOL 귀하의 의견에 대한 내 대답은 귀하의 질문 위에 있습니다 : D (삭제 및 재 게시 ist 대신 댓글을 편집했을 수 있습니다) – doesterr