Skip to content

Instantly share code, notes, and snippets.

@rubiety
Created January 4, 2010 23:42
Show Gist options
  • Save rubiety/268995 to your computer and use it in GitHub Desktop.
Save rubiety/268995 to your computer and use it in GitHub Desktop.
### Don't you wish you could use this if-nil idiom?
first_name || "Joe"
# Well you can't if you expect first_name to be blank instead of nil, so Ruby will short-circuit.
# Enter deblank:
class Object
def deblank
self.blank? ? nil : self
end
end
# Now you can do this:
first_name.deblank || "Joe"
# Instead of this:
first_name.blank ? "Joe" : first_name
# Probably not really worth the added confusion to other developers however, unless it was in ActiveSupport
### Another possibility...
class Object
def otherwise
self.blank? ? yield : self
end
end
# Now you can do this:
first_name.otherwise { "Joe" }
# Instead of this:
first_name.blank ? "Joe" : first_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment