假设数组如下所示
city = ['london', 'new york', 'london', 'london', 'washington']
desired_location = ['london']city & desired_location给了['london']
但我想要['london', 'london', 'london']
发布于 2015-03-03 00:51:11
您可以使用Enumerable#select
city.select {|c| desired_location.include?(c)}
# => ["london", "london", "london"]发布于 2015-03-03 02:34:49
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']@Santosh‘方法返回:
["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} 发布于 2015-03-03 01:05:49
另一种方式:
cities = ['london', 'new york', 'london', 'london', 'washington']
puts cities.select{|city| cities.count(city) > 1}https://stackoverflow.com/questions/28815103
复制相似问题