2014-05-23 2 views
0

when-then 명세서에서 과제를하려고하는데, 예상 한대로 작동하지 않습니다. 내가보기에 문제는, 어쩌면, 경우에 따라, 그리고 때로는 기능과 다른 범위를 가졌기 때문이다. 그래서, 내 변수 message_header을 어떻게 참조하여 올바른 과제를 쓸 수 있습니까? 아니면 다른 것들입니까?사례 명세서 내에서의 할당

def message_notice(type, notice) 
    message_header = "" 
    case 'type' 
     when 'danger' then message_header = 'Oops, something wrong happened' 
     when 'success' then message_header = 'Done' 
     when 'warning' then message_header = 'Hey, be careful' 
     when 'info' then message_header = 'News, news' 
    end 
    return "<strong>#{message_header}!</strong> #{notice}" 
    end 

답변

3
case 'type' 

필요 당신은 당신의 사건이 아닌 변수 type에 상수 문자열 'type'를 제공하고

case type 

수 있습니다. 어떤 문자도 'type'과 같지 않으므로 when은 일치하지 않습니다.

또한 각 분기에서 동일한 모든 할당을 제거하여이를 상당히 정리할 수 있습니다. 모든 것이 루비에서 값으로 평가되므로 case 문은 선택된 분기에서 값을 반환합니다.

def message_notice(type, notice) 
    message_header = case type 
        when 'danger' then 'Oops, something wrong happened' 
        when 'success' then 'Done' 
        when 'warning' then 'Hey, be careful' 
        when 'info' then 'News, news' 
        end 
    "<strong>#{message_header}!</strong> #{notice}" 
end 

당신도 한 단계 더 걸릴 단순히 간단한 매핑과 같은 유형/메시지를 저장할 수 있습니다

def message_notice(type, notice) 
    messages = { 
    'danger' => 'Oops, something wrong happened', 
    'success' => 'Done', 
    'warning' => 'Hey, be careful', 
    'info' => 'News, news' 
    } 

    "<strong>#{messages[type]}!</strong> #{notice}" 
end 
+0

좋아, 나는 어리 석다. 나는 그럴 수 없다. 감사! – tehAnswer

+0

여기에 몇 가지 훌륭한 제안이 있습니다. 그러나 메서드 내에서 해시를 반복적으로 정의하는 것은 약간 낭비입니다. 그것은 모듈 수준 상수로 더 좋을 것입니다. – tadman

+1

, re meagar가 제안한 해시 사용법은 키 대신 문자열 대신 기호를 사용하는 것을 고려합니다 (예 :'danger'보다는': danger'). 그 이유는 [여기] (http://stackoverflow.com/questions/8189416/why-use-symbols-as-hash-keys-in-ruby)에서 논의 된 것처럼 여러 가지입니다. –

0

은 제거 ''의 경우 문에서 유형을 주변. '위험', '성공', ... 문자열 중 하나가 '유형'과 같은지 확인하고 있습니다. 그리고 절대 그렇지 않다.