Skip to content

Instantly share code, notes, and snippets.

@soulcutter
Created October 31, 2024 17:37
Show Gist options
  • Save soulcutter/60430f8112a74d055a791c678e47539f to your computer and use it in GitHub Desktop.
Save soulcutter/60430f8112a74d055a791c678e47539f to your computer and use it in GitHub Desktop.
Enumerating... or else
# 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