Skip to content

Instantly share code, notes, and snippets.

@Ajedi32
Created June 20, 2014 21:05
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 Ajedi32/4c4c93f979fa45a6f2b1 to your computer and use it in GitHub Desktop.
Save Ajedi32/4c4c93f979fa45a6f2b1 to your computer and use it in GitHub Desktop.
Concise way of passing an argument to a method when the argument is not nil
# One line: dead simple.
o = ->(arg) { arg.nil? ? [] : [arg] }
# Usage example:
def some_method(required_arg, optional_arg=:default)
puts "Got required_arg: #{required_arg.inspect}"
puts "Got optional_arg: #{optional_arg.inspect}"
end
pass_this = "Required arg"
maybe_pass_this = nil
# This passes nil explicitly, which we don't want
some_method(pass_this, maybe_pass_this)
# This method is nice, but is sort of bulky
some_method(pass_this, *[maybe_pass_this].compact)
# Pretty and concise
some_method(pass_this, *o[maybe_pass_this])
# If you don't like the name `o`, there are alternatives:
opt = o
some_method(pass_this, *opt[maybe_pass_this])
optional = o
some_method(pass_this, *optional[maybe_pass_this])
# Or you can use parens instead of brackets:
define_singleton_method(:o, &o)
some_method(pass_this, *o(maybe_pass_this))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment