我有一系列電子郵件,需要使用其頂級域將其轉換為哈希:
例子:
["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
Should Return
{
com: ["[email protected]"],
de: ["[email protected]"],
fr: ["[email protected]", "[email protected]"]
}
到目前為止我所做的。
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]"}
我該如何修復,使兩個值都在一個陣列中。
謝謝奧努爾
uj5u.com熱心網友回復:
我該如何修復,使兩個值都在一個陣列中。
您實際上并不是在創建陣列。創建一個并向其附加值。
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 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/330620.html
標籤:红宝石
