2011-10-25 6 views
5

체커 프로그램을 리팩터링하고 플레이어 이동 요청 (예 : "3, 5, 5"형식)을 int로 처리하려고합니다. 정렬. 나는 다음과 같은 방법을 가지고,하지만 난 그게 될 수 알고는 루비 등 생각하지 않습니다리팩터링 루비 : 문자열 배열을 int 배열로 변환

def translate_move_request_to_coordinates(move_request) 
    return_array = [] 
    coords_array = move_request.chomp.split(',') 
    coords_array.each_with_index do |i, x| 
     return_array[x] = i.to_i 
    end 
    return_array 
    end 

내가 다음과 같은 RSpec에 테스트가 있습니다.

it "translates a move request string into an array of coordinates" do 
     player_input = "3, 3, 5, 5" 
     translated_array = @game.translate_move_request_to_coordinates(player_input) 
     translated_array.should == [3, 3, 5, 5] 
    end 

테스트를 통과했지만 코드가 꽤 못 생겼습니다. 어떤 도움을 주시면 감사하겠습니다. 감사.

스티브

답변

22

당신은지도의 조작에 의해 each의 명시적인 반복을 대체 할 수 :

move_request.chomp.split(',').map { |x| x.to_i } 

@tokland에 의해 제안 된이 글을 쓰는에 대한보다 간결한 방법은 다음과 같습니다

move_request.chomp.split(',').map(&:to_i) 

블록을 명시 적으로 작성하지 않고 임의의 이름과 관련이없는 x과 같은 변수 이름을 선택하지 않습니다.

하는 What does to_proc method mean?

+8

move_request.split을 유래 포스트에서 참조하시기 바랍니다 (",")지도. (: to_i) – tokland

+0

+1 : 나는 그것을 몰랐다. 흥미로운 설명은 "Pragmatic Bookshelf"(http://pragprog.com/)의 "Programming Ruby 1.9"에서 "Symbol.to_proc 트릭"(365 페이지, 4th 인쇄, 2011 년 5 월) 섹션에서 흥미로운 설명이 있습니다. – lkuty

관련 문제