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

时间:2015-03-24 23:48:43

标签: ruby hash tostring

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

[{"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封,有时甚至没有。更糟糕的是,甚至可能存在重复。例如两封家庭电子邮件。

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码:

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

答案 1 :(得分:0)

你可以写:

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(aka merge!)的形式,它使用块来确定合并的两个哈希中存在的键的值。

相关问题