5

I'm refactoring a checkers program, and I am trying to process a players move request (in the form of "3, 3, 5, 5" for example) into an int array. I have the following method, but it doesn't feel as Ruby-like as I know it could be:

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

I have the following RSpec test with it.

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 

The test passes, but I think the code is pretty ugly. Any help would be appreciated. Thanks.

Steve

steve_gallagher
  • 3,778
  • 8
  • 33
  • 51

1 Answers1

22

You could replace the explicit iteration of each by a map operation:

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

A more concise way of writing this as proposed by @tokland is :

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

It avoids explicitly writing a block and also choosing a variable name like x which is not relevant as any name would do.

Please have a look at stackoverflow post What does to_proc method mean?

Community
  • 1
  • 1
Ludovic Kuty
  • 4,868
  • 3
  • 28
  • 42
  • 8
    move_request.split(",").map(&:to_i) – tokland Oct 25 '11 at 17:05
  • +1: I didn't know it. There an interesting explanation of it in the book "Programming Ruby 1.9" from the [Pragmatic Bookshelf](http://pragprog.com/) in section "The Symbol.to_proc Trick" on page 363 (4th printing, May 2011). – Ludovic Kuty Oct 26 '11 at 06:17