How to remove duplicate entry from ruby hash -


i have query result hash.

 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 mar, calangute", stars: "3">, #<hotel id: 41, hotel_name: "vijay: krish holiday inn,baga", stars: "2">, #<hotel id: 39, hotel_name: "vijay: estrela mar, calangute", stars: "3">, #<hotel id: 40, hotel_name: "estrela 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 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 mar, calangute", stars: "3">, #<hotel id: 42, hotel_name: "vijay: resort de alturas,candolim", stars: "4"] 

and

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

and want delete duplicate hash value hotels , remain hash like

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

i tried

hotels.uniq { |i| i[:id] }.map(&:id) hotel load (0.4ms)  select distinct `hotels`.* `hotels` inner join `package_prices` on `package_prices`.`hotel_id` = `hotels`.`id` `hotels`.`searchable` = 1 order package_prices.price => [42, 48, 41, 39, 43, 46, 44, 45, 47, 40] 

but changed order want [42, 47, 48, 41, 43, 39, 40, 44, 46, 45]

just call uniq! method change hotels array in-place, uniq! takes block can return comparing

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

e.g. see usage

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">] 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -