-
-
Save ajlai/4272922 to your computer and use it in GitHub Desktop.
Making Ruby || / && chaining for non nil/false values nicer
This file contains hidden or 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
class Object | |
# Usage: | |
# maybe_zero.self_unless(&:zero?) || zero_fallback | |
# # => either maybe_zero or zero_fallback (if maybe_zero was zero) | |
def self_unless | |
self unless yield(self) | |
end | |
# Usage: | |
# maybe_present.self_if(&:present?) | |
# # => maybe_present or false if maybe_present is not present (basically implementing http://apidock.com/rails/Object/presence) | |
def self_if | |
self if yield(self) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment