如何在重复ruby的数组中找到公共元素

时间:2015-03-02 16:47:14

标签: ruby-on-rails ruby arrays

让我们说数组如下所示

city = ['london', 'new york', 'london', 'london', 'washington']

desired_location = ['london']

city & desired_location提供['london']

但我想要['london', 'london', 'london']

3 个答案:

答案 0 :(得分:2)

您可以使用Enumerable#select

city.select {|c| desired_location.include?(c)}
# => ["london", "london", "london"]

答案 1 :(得分:1)

cities = ['london', 'new york', 'london', 'london', 'washington']

如果desired_location包含单个元素:

desired_location = ['london']

我推荐@ santosh的解决方案,但这也有效:

desired_location.flat_map { |c| [c]*cities.count(c) }
  #=> ["london", "london", "london"]

假设desired_location包含多个元素(我认为这是可能的,否则就不需要它成为一个数组):

desired_location = ['london', 'new york']

@桑托什'方法返回:

["london", "new York", "london", "london"]

这很可能是你想要的。如果您希望将它们分组:

desired_location.flat_map { |c| [c]*cities.count(c) }
  #=> ["london", "london", "london", "new york"]

或:

desired_location.map { |c| [c]*cities.count(c) }
  #=> [["london", "london", "london"], ["new york"]]

根据您的要求,您可能会发现生成哈希更有用:

Hash[desired_location.map { |c| [c, cities.count(c)] }]
  #=> {"london"=>3, "new york"=>1} 

答案 2 :(得分:0)

另一种方式:

cities = ['london', 'new york', 'london', 'london', 'washington']
puts cities.select{|city| cities.count(city) > 1}