Search code examples
rubyruby-on-rails-6ruby-2.3ruby-3

Ruby on rails, How to compare two hashesh value to each other's?


I am trying compare one hash values to another hash values of perticular each key's. like below as

db_data = [{"user_id"=>"000879", "dept"=>"1066", "type"=>"A", "rate"=>"999"},
          {"user_id"=>"000879", "dept"=>"1066","type"=>"AB", "rate"=>"999"},
          {"user_id"=>"008118", "dept"=>"10000869", "type"=>"A", "rate"=>"950"}]

file_data = [{"user"=>"00094967",  "dept_id"=>"0020",  "price"=>950, "div_type"=>"A"},
            {"user"=>"00094967", "dept_id"=>"0020",  "price"=>950, "div_type"=>"A"},
            {"user"=>"00094967",  "dept_id"=>"0020", "price"=>950, "div_type"=>"AB"}]

I need to compare specific key of value from first hash data to compare with second hash specific key of value to each. like from file_data dept_id compare to db_data all keys dept value and if not getting then store in varaible(different data store)


Solution

  • results = []
    existed = false
    file_data.each do |fd|
      dept_id = fd['dept_id']
      db_data.each do |dd|
        if dept_id == dd['dept']
          existed = true
          break
        end
      end
      results << fd if existed == false
    
      existed = false
    end
    
    # {"user"=>"00094967", "dept_id"=>"0020", "price"=>950, "div_type"=>"A"}
    # {"user"=>"00094967", "dept_id"=>"0020", "price"=>950, "div_type"=>"A"}
    # {"user"=>"00094967", "dept_id"=>"0020", "price"=>950, "div_type"=>"AB"}
    # because dept_id 0020 is not existed in db_data, so it will go to result
    

    so if dept_id is existed in the first loop on db_data it will not store the data to result. if until last element of db_data is not existed then it will go to result. then the flag existed will reset to false again.

    Maybe that is not rubyist way, but it will do