Skip to content

Instantly share code, notes, and snippets.

@brainopia
Created February 9, 2012 14:21
Show Gist options
  • Save brainopia/1780302 to your computer and use it in GitHub Desktop.
Save brainopia/1780302 to your computer and use it in GitHub Desktop.
# 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
# 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