Created
October 31, 2024 17:37
-
-
Save soulcutter/60430f8112a74d055a791c678e47539f to your computer and use it in GitHub Desktop.
Enumerating... or else
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
# Written based on a conversation about enumerating with behavior for | |
# empty collections | |
# | |
# https://ruby.social/@pushcx/113397079757804801 | |
# https://www.justinweiss.com/articles/each-dot-dot-dot-or-else/ | |
module OtherwiseEnumerable | |
refine Enumerable do | |
def otherwise | |
return yield if empty? | |
self | |
end | |
end | |
end | |
using OtherwiseEnumerable | |
[1, 2, 3].select(&:odd?).otherwise { [42] }.each { |x| puts x } | |
[2, 2, 4].select(&:odd?).otherwise { [42] }.each { |x| puts x } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment