重构此代码以提高可读性

时间:2013-02-17 12:09:21

标签: ruby arrays

请查看以下代码

def test
  array = Array.new
  array2 = Array.new

  groups = [[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]]
  type = ["goa", "mumbai"]
  groups.each_with_index do |item,index|

       if item.include?(type[0]) == true
         array << index  << array2
        elsif item.include?(type[1]) == true
               array2 << index 
       else
         "nothing ;)"
       end

  end
  print array.each_slice(2).map { |a, b| [a, b.first] }
end
combine

#Output - [[0, 1], [2, 1]]

查看代码问题?那就是我使用了一堆if和else语句。如果type数组有超过2个条目,该怎么办?我不能继续写if和elsif语句。那就是我需要你帮助的地方。什么是更好的结构代码?循环?如果是这样的话。

1 个答案:

答案 0 :(得分:2)

这是我的代码。

def combinations(groups, types)
  array = Array.new(types.size) { Array.new([]) }
  groups.each_with_index do |item, index|
     types.each_with_index { |type, i| array[i] << index if item.include? type }
  end

  flat = array.inject { |acc, i| acc.product i }.flatten
  flat.each_slice(types.size).to_a
end

示例测试用例

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]], ["goa", "mumbai"])

输出:[[0, 1], [2, 1]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]], ["goa", "africa"])

输出:[[0, 2], [2, 2]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"], [123, "india"]], ["goa", "mumbai", "india"])

输出:[[0, 1, 3], [2, 1, 3]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "mumbai", "goa"], [123, "india"]], ["goa", "mumbai", "india", "italy"])

输出:[[0, 1, 3, 0], [0, 2, 3, 0], [2, 1, 3, 0], [2, 2, 3, 0]]

如果我理解你的问题,那么这些应该是正确的。虽然我可能误解了你。请告诉我如果我的问题出错了,如果你能提供很好的测试用例。