0

我有查询结果哈希。

 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]

4

3 回答 3

2

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

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

例如查看用法

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">]
于 2013-09-24T19:48:39.153 回答
0

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

hotel_hash.map(&:id).uniq

于 2013-09-24T19:08:45.997 回答
-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]

于 2013-09-24T19:38:50.363 回答