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 に答える