Skip to content

Instantly share code, notes, and snippets.

@fairchild
Created April 15, 2012 16:52
Show Gist options
  • Select an option

  • Save fairchild/2393815 to your computer and use it in GitHub Desktop.

Select an option

Save fairchild/2393815 to your computer and use it in GitHub Desktop.
merge a hash, only updating the first hash with values from the second where the first
# merge a hash, only updating the first hash with values from the second where the first already has an exisitng key
# for example,
# a= {"a"=>1, "b"=>2, "z"=>3}
# b= {"x"=>99, "y"=>88, "z"=>77}
# will result in {"a"=>1, "b"=>2, "z"=>77}
def update_existing(a, b)
a.inject({}){|sum, el| (b.has_key?(el.first) && b[el.first]) ? sum.update(el.first=>b[el.first]) : sum[el.first]=a[el.first]; sum}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment