5
我正在重構一個跳棋程序,並且我正在嘗試處理一個玩家移動請求(例如「3,3,5,5」的形式)爲int陣列。我有以下的方法,但並不覺得紅寶石般的,因爲我知道這可能是:重構Ruby:將字符串數組轉換爲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
該測試通過,但我認爲代碼是非常醜陋的。任何幫助,將不勝感激。謝謝。
史蒂夫
move_request.split( 「」)的地圖。(:to_i) – tokland
+1:我不知道。在第363頁(2011年5月第4次印刷)的「Symbol.to_proc技巧」一節的[Pragmatic Bookshelf](http://pragprog.com/)中的「Programming Ruby 1.9」一書中有一個有趣的解釋。 – lkuty