【问题标题】:Refactoring Ruby : Converting string array to int array重构 Ruby:将字符串数组转换为 int 数组
【发布时间】:2011-12-15 02:19:01
【问题描述】:

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

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

测试通过了,但我认为代码很丑。任何帮助,将不胜感激。谢谢。

史蒂夫

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您可以用 map 操作替换 each 的显式迭代:

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

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

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

    它避免了显式地编写一个块,也避免了选择像x这样的变量名,这与任何名称都不相关。

    请查看stackoverflow 帖子What does to_proc method mean?

    【讨论】:

    • move_request.split(",").map(&:to_i)
    • +1:我不知道。在第 363 页(第 4 次印刷,2011 年 5 月)的“Symbol.to_proc 技巧”部分的Pragmatic Bookshelf 中的“Programming Ruby 1.9”一书中有一个有趣的解释。
    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2021-12-21
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多