저는 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
조건에 도달하지 않았다. 이것은 나를 혼란스럽게합니다. 내가 뭘 잘못하고 있는거야?
'case key_int'대신'case'를 사용해야합니다. – Stefan
나는 뭔가를 놓쳤는가? 이 블로그는 달리 말하길 http://blog.honeybadger.io/rubys-case-statement-advanced-techniques/ –
블로그 포스트는 람다와 커스텀 matcher 클래스를 사용하여'=='와'<'를 통해 비교합니다. – Stefan