Home > OS >  Return a Hash Grouped by Top Level Domains
Return a Hash Grouped by Top Level Domains

Time:10-21

I have an array of emails that I need to convert into a Hash using their Top Level Domain:

Example:


["[email protected]", "[email protected]", "[email protected]", "[email protected]"]

Should Return

{
  com:  ["[email protected]"],
  de:   ["[email protected]"],
  fr:   ["[email protected]", "[email protected]"]
}

What I have done so far.


def group_by_tld(emails)
  # TODO: return a Hash with emails grouped by TLD
  new_hash = {}
  emails.each do |e|
    last_el = e.partition(".").last
    if last_el == e.partition(".").last
      new_hash[last_el] = e
    else
      break
    end
  end
   return new_hash
end


Output: {"fr"=>"[email protected]", "com"=>"[email protected]", "de"=>"[email protected]"}

How can I fix so both values are in an array.

Thanks Onur

CodePudding user response:

How can I fix so both values are in an array.

You're not actually creating an array. Do create one and append values to it.

new_hash[last_el] ||= [] # make sure array exists, and don't overwrite it if it does
new_hash[last_el] << e

Alternatively, this whole snippet can be replaced with

emails.group_by{|e| e.partition(".").last }
  •  Tags:  
  • ruby
  • Related