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

5

我正在重构一个跳棋程序,并尝试将玩家的移动请求(例如“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

我有以下带有it的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 

测试通过了,但我认为代码非常丑陋。任何帮助将不胜感激。谢谢。
Steve
1个回答

22
你可以通过使用map操作来替换对each的显式迭代:
move_request.chomp.split(',').map { |x| x.to_i }

@tokland 提出的更简洁的写法是:

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

它避免了显式编写代码块,也避免了选择一个像 x 这样不相关的变量名。

请查看 stackoverflow 帖子“to_proc 方法是什么意思?”


8
将move_request字符串以逗号为分隔符进行拆分,并将拆分后的每个子字符串转换为整数类型,最终返回一个整数类型的数组。 - tokland
+1:我之前不知道这个。在《Programming Ruby 1.9》这本书的第363页(2011年5月第4版)的“Symbol.to_proc Trick”一节中,Pragmatic Bookshelf提供了一个有趣的解释。 - Ludovic Kuty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接