Created
February 8, 2016 06:07
-
-
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.
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
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