Skip to content

Instantly share code, notes, and snippets.

@tehprofessor
Created February 8, 2016 06:07
Show Gist options
  • Save tehprofessor/11f274075f2c0c924bca to your computer and use it in GitHub Desktop.
Save tehprofessor/11f274075f2c0c924bca to your computer and use it in GitHub Desktop.
Ruby 2.3's safe navigation operator allows for a pretty nice "or else" construct.
module OrElse
module ObjectImplementation
def or_else(_)
self
end
end
module NilClassImplementation
def or_else(val)
val
end
end
end
class Object
include OrElse::ObjectImplementation
end
class NilClass
include OrElse::NilClassImplementation
end
# Example
user_hash = {id: nil}
user_hash[:id]&.or_else(1)
# => 1
user_hash[:id] = 2
user_hash[:id]&.or_else(1)
# => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment