Skip to content

Instantly share code, notes, and snippets.

@mzemel
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save mzemel/cb6c91bb56dad7628dfd to your computer and use it in GitHub Desktop.

Select an option

Save mzemel/cb6c91bb56dad7628dfd to your computer and use it in GitHub Desktop.
What do
########
# Hash #
########
def function(opts)
request = {}
request[:name] = opts[:name] if opts[:name]
request[:email] = opts[:email] if opts[:email]
request[:address] = opts[:name] if opts[:name]
post_to_service(request)
end
# Call it with:
function(name: "Bob", email: "test@foo.bar", address: "123 Fake St.")
function(name: "Bob", email: "test@foo.bar", address: nil)
################
# List of args #
################
def function(name, email = "bar@baz.qux", address = nil)
request = {}
request[:name] = name
request[:email] = email
request[:address] = address if address.present?
post_to_service(request)
end
# Call it with
function(name = "Bob", email = "test@foo.bar", address = "123 Fake St.")
function(name = "Bob", email = "test@foo.bar")
function(name = "Bob")
@zachweed

Copy link
Copy Markdown

You can really just accomplish the problem like below. Basically all you are doing in your first 'function' is cloning the hash into another hash called request. Just accept the param as hash and default the param to a empty hash and whatever keys aren't passed won't be passed and the opposite goes for the opposite.

def function(request = {})
    post_to_service(request)
end

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