Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Created January 30, 2014 22:14
Show Gist options
  • Save stevenharman/8721133 to your computer and use it in GitHub Desktop.
Save stevenharman/8721133 to your computer and use it in GitHub Desktop.
Ruby's Hash#merge with an optional block to resolve key conflicts.
# via @avdi's RubyTapas Episode 170: http://www.rubytapas.com/episodes/170-Hash-Merge
headers = <<END
Accept: */*
Set-Cookie: foo=42
Set-Cookie: bar=23
END
def parse_headers(headers)
headers.lines.reduce({}) { |result, line|
name, value = line.split(':')
result.merge(name.strip => value.strip)
}
end
parse_headers(headers)
#=> {"Accept"=>"*/*", "Set-Cookie"=>"bar=23"}
def parse_headers(headers)
headers.lines.reduce({}) { |result, line|
name, value = line.split(':')
result.merge(name.strip => value.strip) { |key, left, right|
Array(left) + Array(right)
}
}
end
parse_headers(headers)
#=> {"Accept"=>"*/*", "Set-Cookie"=>["bar=42", "bar=23"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment