重新编译此代码以提高可读性



请查看以下代码

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语句了。这就是我需要你帮助的地方。什么是更好的代码结构?循环?如果是,如何。

这是我的代码。

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]]

如果我正确理解你的问题,那么这些应该是正确的。尽管我可能误解了你。请告诉我,如果我弄错了你的问题,如果你能提供测试用例,那就太好了。

最新更新