Skip to content

Instantly share code, notes, and snippets.

@AJFaraday
Created September 28, 2020 15:53
Show Gist options
  • Save AJFaraday/791d7a997768151d7ec5b06a27a65b8a to your computer and use it in GitHub Desktop.
Save AJFaraday/791d7a997768151d7ec5b06a27a65b8a to your computer and use it in GitHub Desktop.
Possibly the best monkey patch I've ever written
class NilClass
def method_missing(m, *args, &block)
if [String, Integer, Float, Time].any?{|kls| kls.method_defined?(m)}
nil
else
super
end
end
end
x = 'string'
puts x.upcase.strip.rjust(10).inspect
# " STRING"
x = nil
puts x.upcase.strip.rjust(10).inspect
# nil
x = Time.now
puts (x + 1.day).strftime("%d of %B, %Y").rjust(50).inspect
# " 29 of September, 2020"
x = nil
puts (x + 1.day).strftime("%d of %B, %Y").rjust(50).inspect
# nil
x = 20.0
puts (x + 2 * 50 / 2 % 3 * (3 * 4)).inspect
# 44.0
x = nil
puts (x + 2 * 50 / 2 % 3 * (2/ 4)).inspect
# nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment