重构Ruby:将字符串数组转换为int数组

ste*_*her 5 ruby rspec

我正在重构一个跳棋程序,我试图将玩家移动请求(例如"3,3,5,5"的形式)处理成一个int数组.我有以下方法,但它不像我所知的那样感觉像Ruby一样:

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
Run Code Online (Sandbox Code Playgroud)

我用它进行了以下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 
Run Code Online (Sandbox Code Playgroud)

测试通过,但我认为代码非常难看.任何帮助,将不胜感激.谢谢.

史蒂夫

Lud*_*uty 22

您可以each通过map操作替换显式迭代:

move_request.chomp.split(',').map { |x| x.to_i }
Run Code Online (Sandbox Code Playgroud)

@tokland提出的更简洁的写作方式是:

move_request.chomp.split(',').map(&:to_i)
Run Code Online (Sandbox Code Playgroud)

它避免显式写一个块,并选择一个变量名称,就像x任何名称都不相关.

请看一下stackoverflow post to_proc方法是什么意思?

  • move_request.split( "")的地图(&:to_i). (8认同)