Skip to content

Instantly share code, notes, and snippets.

@ajlai
Forked from anonymous/self_unless.rb
Created December 13, 2012 00:14
Show Gist options
  • Save ajlai/4272922 to your computer and use it in GitHub Desktop.
Save ajlai/4272922 to your computer and use it in GitHub Desktop.
Making Ruby || / && chaining for non nil/false values nicer
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