返回按顶级域分组的散列

  • 本文关键字:返回 ruby
  • 更新时间 :
  • 英文 :


我有一个数组的电子邮件,我需要转换成哈希使用他们的顶级域名:

的例子:


["kevin@yahoo.fr", "edward@gmail.fr", "julien@mdn.com", "dimitri@berlin.de"]
Should Return
{
com:  ["julien@mdn.com"],
de:   ["dimitri@berlin.de"],
fr:   ["kevin@yahoo.fr", "edward@gmail.fr"]
}

我到目前为止所做的。


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"=>"edward@gmail.fr", "com"=>"julien@mdn.com", "de"=>"dimitri@berlin.de"}

我如何修复,使两个值都在一个数组。

谢谢会偏向

如何修复,使两个值都在一个数组中

你实际上并没有创建一个数组。一定要创建一个,并给它附加值。

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

或者,整个代码段可以替换为

emails.group_by{|e| e.partition(".").last }

最新更新