解析哈希以打印成格式良好的字符串

Parsing a hash to print into a nicely formatted string

我有以下数组(它是更大散列的一部分):

[{"type"=>"work", "value"=>"work@work.com"}, {"type"=>"home", "value"=>"home@home.com"}, {"type"=>"home", "value"=>"home2@home2.com"}]

我想以某种方式将其转换为格式整齐的字符串,例如:

Work: work@work.com, Home: home@home.com, Home: home2@home2.com

问题是这个数组现在总是相同的,有时会有 2 封电子邮件,有时 5 封,有时 none。更糟糕的是,甚至可能存在重复。例如,两个家庭电子邮件。

您可以使用以下代码:

array = [{"type"=>"work", "value"=>"work@work.com"}, {"type"=>"home", "value"=>"home@home.com"}]

string = array.map do |item|
    item = "#{item['type'].capitalize}: #{item['value']}"
end.join(", ")

puts string

输出:

Work: work@work.com, Home: home@home.com, Home: home2@home2.com

你可以这样写:

arr = [{ "type"=>"work",    "value"=>"work@work.com"    },
       { "type"=>"home",    "value"=>"home@home.com"    },
       { "type"=>"cottage", "value"=>"cot1@cottage.com" },
       { "type"=>"home",    "value"=>"home2@home2.com"  },
       { "type"=>"cottage", "value"=>"cot2@cottage.com" }]

h = arr.each_with_object({}) { |g,h|
  h.update(g["type"]=>[g["value"]]) { |_,o,n| o+n } }
  #=> {"work"=>["work@work.com"],
  #    "home"=>["home@home.com", "home2@home2.com"],
  #    "cottage"=>["cot1@cottage.com", "cot2@cottage.com"]}

puts h.map { |k,v| "#{k.capitalize}: #{v.join(', ')}" }.join("\n")
  # Work: work@work.com
  # Home: home@home.com, home2@home2.com
  # Cottage: cot1@cottage.com, cot2@cottage.com

这使用 Hash#update(又名 merge!)的形式,使用块来确定要合并的两个哈希中存在的键的值。