Created
June 20, 2014 21:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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