-
-
Save brainopia/1780302 to your computer and use it in GitHub Desktop.
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
# famous trick from The Ruby Way to detect whether default value was used or not | |
def foobar(variable=((default=true);:value)) | |
p variable, default | |
end | |
foobar :value # => default = nil | |
foobar # => default = true | |
# right way (won't work for nil and false but who cares) | |
def foobar(variable=nil) | |
default = not variable | |
variable ||= :value | |
end | |
# right way in case somebody cares about nil and false O_O | |
def foobar(variable=:__default__) | |
if variable == :__default__ | |
default = true | |
variable = :value | |
end | |
end |
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
# variation of this trick to handle arrays and splatted arrays | |
def coordinates(x, y=(x,_ = x; _)) | |
p x, y | |
end | |
coordinates [1,2] # => 1, 2 | |
coordinates 1, 2 # => 1, 2 | |
# right way | |
def coordinates(*args) | |
x, y = args.flatten | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment