0

I am stuck in a situation where I need to find missing key in the hash. But the problem is key is not certain it can be any key out of certain keys.

For example

 {"from"=>"abc@gmail.com", "to"=>"def@gmail.com:ijk@gmail.com:lmn@gmail.com", "subject"=>"hi", "body"=>"there", "cc" => "def@gmail.com:ijk@gmail.com", "bcc" => "def@gmail.com:ijk@gmail.com"}

Missing keys can be from, subject, to, body but not cc and bcc. So I need to find out which of the keys are missing in a hash in order to return the specific key to the user. I cannot do this at the model level This solution provided in this link is not helpful because it is just returning me true or false. Instead of that, I need the missing keys which are not present in my hash

ankur
  • 293
  • 1
  • 5
  • 19
  • You didn't read my question properly. The link which you have provided in that it will return me true or false only. It won't return me the specific key which is missing inside my hash – ankur Apr 04 '18 at 03:52
  • 1
    If `h` is your hash, is '['from', 'subject', 'to', 'body'] - h.keys` what you want? – Cary Swoveland Apr 04 '18 at 04:04
  • @CarySwoveland - Sorry My bad I didn't check the 2nd example It is working thanks – ankur Apr 04 '18 at 07:04

1 Answers1

3

You can make use of the Hash#keys method

REQUIRED_KEYS = %w(from subject to body)
hash = {
  "from"=>"abc@gmail.com", 
  "to"=>"def@gmail.com:ijk@gmail.com:lmn@gmail.com", 
  "subject"=>"hi", 
  "body"=>"there", 
  "cc" => "def@gmail.com:ijk@gmail.com", 
  "bcc" => "def@gmail.com:ijk@gmail.com"
}

REQUIRED_KEYS - hash.keys
#=> []

hash.delete('to')
#=> "def@gmail.com:ijk@gmail.com:lmn@gmail.com"

REQUIRED_KEYS - hash.keys
#=> ["to"]
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88