Zack
Zack

Reputation: 2497

Parsing a hash to print into a nicely formatted string

I have the following array (which is part of a much larger hash):

[{"type"=>"work", "value"=>"[email protected]"}, {"type"=>"home", "value"=>"[email protected]"}, {"type"=>"home", "value"=>"[email protected]"}]

I would like somehow take that and convert it to a neatly formatted string such as:

Work: [email protected], Home: [email protected], Home: [email protected]

The issue is that this array will now always be the same, sometime it will have 2 emails, sometimes 5, sometimes none. And what is worse is that there can even be duplicates. two home emails for example.

Upvotes: 2

Views: 957

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You could write:

arr = [{ "type"=>"work",    "value"=>"[email protected]"    },
       { "type"=>"home",    "value"=>"[email protected]"    },
       { "type"=>"cottage", "value"=>"[email protected]" },
       { "type"=>"home",    "value"=>"[email protected]"  },
       { "type"=>"cottage", "value"=>"[email protected]" }]

h = arr.each_with_object({}) { |g,h|
  h.update(g["type"]=>[g["value"]]) { |_,o,n| o+n } }
  #=> {"work"=>["[email protected]"],
  #    "home"=>["[email protected]", "[email protected]"],
  #    "cottage"=>["[email protected]", "[email protected]"]}

puts h.map { |k,v| "#{k.capitalize}: #{v.join(', ')}" }.join("\n")
  # Work: [email protected]
  # Home: [email protected], [email protected]
  # Cottage: [email protected], [email protected]

This uses the form of Hash#update (aka merge!) that uses a block to determine the values of keys that are present in both hashes being merged.

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157967

You could use the following code:

array = [{"type"=>"work", "value"=>"[email protected]"}, {"type"=>"home", "value"=>"[email protected]"}]

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

puts string

Output:

Work: [email protected], Home: [email protected], Home: [email protected]

Upvotes: 2

Related Questions