如何从ruby哈希中删除重复的条目

时间:2013-09-24 18:53:49

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

我有查询结果哈希。

 hotels = [#<Hotel id: 42, hotel_name: "Vijay: Resort De Alturas,Candolim", stars: "4">, #<Hotel id: 42, hotel_name: "Vijay: Resort De Alturas,Candolim", stars: "4">, #<Hotel id: 47, hotel_name: "locard", stars: "3", >, #<Hotel id: 48, hotel_name: "testtttt", stars: "1">, #<Hotel id: 41, hotel_name: "Vijay: Krish Holiday Inn,Baga", stars: "2">, #<Hotel id: 43, hotel_name: "Indian hotel", stars: "3">, #<Hotel id: 39, hotel_name: "Vijay: Estrela Do Mar, Calangute", stars: "3">, #<Hotel id: 41, hotel_name: "Vijay: Krish Holiday Inn,Baga", stars: "2">, #<Hotel id: 39, hotel_name: "Vijay: Estrela Do Mar, Calangute", stars: "3">, #<Hotel id: 40, hotel_name: "Estrela Do Mar, Calangute", stars: "3">, #<Hotel id: 44, hotel_name: "Taj hotel", stars: "3">, #<Hotel id: 46, hotel_name: "mobile hotel", stars: "3">, #<Hotel id: 41, hotel_name: "Vijay: Krish Holiday Inn,Baga", stars: "2">, #<Hotel id: 40, hotel_name: "Estrela Do Mar, Calangute", stars: "3">, #<Hotel id: 47, hotel_name: "locard", stars: "3">, #<Hotel id: 45, hotel_name: "The malwa", stars: "3">, #<Hotel id: 40, hotel_name: "Estrela Do Mar, Calangute", stars: "3">, #<Hotel id: 42, hotel_name: "Vijay: Resort De Alturas,Candolim", stars: "4"]

hotels.map(&:id)
=> [42, 42, 47, 48, 41, 43, 39, 41, 39, 40, 44, 46, 41, 40, 47, 45, 40, 42]

我希望从hotels中删除重复的哈希值,并保持哈希状态

hotels.map(&:id)
=>  [42, 47, 48, 41, 43, 39, 40, 44, 46, 45]

我试过

hotels.uniq { |i| i[:id] }.map(&:id)
Hotel Load (0.4ms)  SELECT DISTINCT `hotels`.* FROM `hotels` INNER JOIN `package_prices` ON `package_prices`.`hotel_id` = `hotels`.`id` WHERE `hotels`.`searchable` = 1 ORDER BY package_prices.price
=> [42, 48, 41, 39, 43, 46, 44, 45, 47, 40]

但这改变了我想要的顺序[42, 47, 48, 41, 43, 39, 40, 44, 46, 45]

3 个答案:

答案 0 :(得分:2)

只需调用uniq!方法就地更改酒店数组,uniq!需要一个区块,您可以返回您要比较的内容

hotels.uniq!{|hotel| hotel.id}

e.g。见用法

irb(main):001:0> class Hotel
irb(main):002:1> attr_reader :id
irb(main):002:1> def initialize(id, name)
irb(main):003:2> @id = id
irb(main):004:2> @name = name
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):008:0> hotels = [Hotel.new(1,'one'), Hotel.new(1,'one'), Hotel.new(2,'two'), Hotel.new(2,'two')]
=> [#<Hotel:0x007fa6b9148c48 @id=1, @name="one">, #<Hotel:0x007fa6b9148b58 @id=1, @name="one">, #<Hotel:0x007fa6b9148a40 @id=2, @name="two">, #<Hotel:0x007fa6b9148950 @id=2, @name="two">]
irb(main):013:0> hotels.uniq!{|hotel| hotel.id}
=> [#<Hotel:0x007fa6b9148c48 @id=1, @name="one">, #<Hotel:0x007fa6b9148a40 @id=2, @name="two">]

答案 1 :(得分:0)

你实际上只是略微偏离轨道。

hotel_hash.map(&:id).uniq

答案 2 :(得分:-3)

我找到了问题的解决方案

@hotels = []
hotels.map{|hotel| @hotels << hotel unless @hotels.map(&:id).include? hotel.id}

现在@hotels.map(&:id)返回[42, 47, 48, 41, 43, 39, 40, 44, 46, 45]