如何比较和拒绝具有不同维度的数组项目?

时间:2018-08-09 19:08:55

标签: arrays ruby match

我有一个一维数组,像这样:

topics = ["Cats", "Dogs", "Fish", "Snakes"]

我还有一个多维数组,其中包含每种动物类型的更多详细信息,但也按属对它们进行了分类:

genus = [["mammals",["Dogs", "Cats", "Tigers"]],
         ["reptiles", ["Snakes", "Lizards"]],
         ["amphibians", ["Fish", "Frogs", "Salamander"]]]

我要做的是将topicsgenus进行比较,并通过删除genus中未包含的种类来修改topics数组,但是我想要保留父属(如果它们具有匹配的值)。如果找不到匹配的值,则应从新数组中删除整个属。最终结果将是:

genus = [["mammals", ["Dogs", "Cats"]],
        ["reptiles",  ["Snakes"]],
        ["amphibians", ["Fish"]]]

我通过迭代topics并拒绝不匹配的种类尝试了一些方法,但似乎在第一次迭代中拒绝了一切,使后续迭代变得毫无意义。

我已经尝试过select并将匹配项推到一个新的数组中,这使我离得更近...但是我宁愿更新现有的数组而不是创建一个新数组。 (这也没有考虑将属保留为数组的一部分。)

有帮助,有帮助!

我尝试过的事情:

genus_list = Array.new

topics.each do |topic|
    matched = genus.select { |type, species| species == topic }
    genus_list.push(matched)
end

2 个答案:

答案 0 :(得分:0)

在我看来,这似乎是解决问题的一种蛮力方法,但这是目前我能想到的最好的方法。这将修改genus个数组

# these are as yours in the question, with the addition of a dinosaur genus to show
# that group gets removed from the end result
topics = ["Cats", "Dogs", "Fish", "Snakes"]
genus = [
  ["mammals",
    ["Dogs", "Cats", "Tiger"] ],
  ["reptiles",
    ["Snakes", "Lizards"] ],
  ["amphibians",
    ["Fish", "Frogs", "Salamander"]],
  ["dinosaur",
     ["Tyrannosaurus", "Pterodactyl"]]
]


genus.reject! do |_, animal_types|
  animal_types.reject! { |type| !topics.include?(type) }

  animal_types.empty?
end

p genus
# => [["mammals", ["Dogs", "Cats"]],
#     ["reptiles", ["Snakes"]],
#     ["amphibians", ["Fish"]]]

答案 1 :(得分:0)

topics = ["Cats", "Dogs", "Fish", "Snakes"]

genus = [
  ["mammals", ["Dogs", "Cats", "Birds"]],
  ["reptiles", ["Snakes", "Lizards"]],
  ["amphibians", ["Fish", "Frogs", "Salamander"]],
  ["birds", ["Bluebirds", "Finches"]]
]

genus = genus.each_with_object([]) do |(vertibrate_class, species), arr|
  selective_species = species & topics
  arr << [vertibrate_class, selective_species] unless selective_species.empty?
end
  #=> [["mammals", ["Dogs", "Cats"]],
  #    ["reptiles", ["Snakes"]],
  #    ["amphibians", ["Fish"]]]