Skip to content

Instantly share code, notes, and snippets.

@freeformz
Created October 17, 2011 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freeformz/1293428 to your computer and use it in GitHub Desktop.
Save freeformz/1293428 to your computer and use it in GitHub Desktop.
merge defaults, preserving existing entries .. Is there a better way?
class Hash
def with_defaults(defaults={})
self.merge(defaults) { |k,o,n| o }
end
def with_defaults!(defaults={})
self.merge!(defaults) { |k,o,n| o }
end
end
@freeformz
Copy link
Author

Use case:

def some_method(opts={})
  opts.with_defaults!(some_default: true, other_default: "bob")
  #...do stuff....
end

some_method( some_default: false )
# opts becomes: { some_default: false, other_default: "bob" }

And I hate doing it the other way. feels wrong.

opts = {some_default: true, other_default: "bob"}.merge!(opts)

and #new is klunky and doesn't actually do what I want

Am I missing something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment