2016-11-09 3 views
2

저는 5면 여섯 명의 역할에 따라 점수를 매기는 kata를하고 있습니다. 여기 내 코드는 지금까지입니다 : 내가 해시의 상태를 얻을조건이 사실 임에도 불구하고 왜 내 사례 설명이 실패합니까?

이 예를 들어 기본적인 수준에서
def score(dice) 
    points = [] 
    score = {} 
    dice.each do |n| 
     if score.has_key?(n.to_s.to_sym) 
     score[n.to_s.to_sym] += 1 
     else 
     score[n.to_s.to_sym] = 1 
     end 
    end 

    score.each do |k,v| 
     key_int = k.to_s.to_i 

     case key_int 
     when key_int == 1 && (v == 3) 
     points << 1000 
     when key_int == 6 && (v == 3) 
     points << 600 
     when key_int == 5 && (v == 3) 
     points << 500 
     when key_int == 4 && (v == 3) 
     points << 400 
     when key_int == 3 && (v == 2) 
     points << 300 
     when key_int == 2 && (v == 3) 
     puts "did I get here" 
     points << 200 
     when key_int == 1 && (v < 3) 
     points << key_int * v 
     when key_int == 5 && (v < 3) 
     points << key_int * v 
     else 
     puts "Default" 
    end 
    end 
    points 
end 

puts score([2, 2, 2, 3, 3]) ==> 200 

그래서이되어 무슨 일이 일어나고 있는지 내 각 루프가 칠 때 :

key_int == 2 && (v == 3) 

및 삽입 case 문 앞의 코드는 true이지만 결코 절대로 points << 200의 조건에 도달하지 않습니다. 단순화를 위해 케이스 로직에 대한 코드를 작성했습니다.

score.each do |k,v| 
    key_int = k.to_s.to_i 
    case key_int 
    when key_int == 2 
    puts "I reached the condition" 
    else 
    puts "default" 
    end 
end 

는 여전히 기본을 얻고 나는 when 조건에 도달하지 않았다. 이것은 나를 혼란스럽게합니다. 내가 뭘 잘못하고 있는거야?

+2

'case key_int'대신'case'를 사용해야합니다. – Stefan

+0

나는 뭔가를 놓쳤는가? 이 블로그는 달리 말하길 http://blog.honeybadger.io/rubys-case-statement-advanced-techniques/ –

+0

블로그 포스트는 람다와 커스텀 matcher 클래스를 사용하여'=='와'<'를 통해 비교합니다. – Stefan

답변

4

case 바로 뒤에 개체를 지정하면 pattern === object을 통해 각각 when 패턴과 비교됩니다.

는 이런 key_int == 2 대해 key_int 비교한다 :이 예에서

(key_int == 2) === key_int 

key_int2이라고 가정은 위에서 언급된다 :

true === 2 

는 평가 된 ~까지 false. 또 다른 예를 들어 case Expression

case 
when key_int == 2 
    # ... 
end 

참조 루비의 설명서 :

는 초기 오브젝트를 생략해야 if-elsif 표현처럼 case 표현을 사용합니다.

관련 문제