Skip to content

Instantly share code, notes, and snippets.

@jasonleonhard
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonleonhard/6d372a18acd0d98be047 to your computer and use it in GitHub Desktop.
Save jasonleonhard/6d372a18acd0d98be047 to your computer and use it in GitHub Desktop.
MONKEY PATCHING: Class and Method examples
# MONKEY PATCHING: Reopen and Add to Any Class in Ruby, including Gems and core Ruby.
# CLASS: naively sum elements in an Array
[1,2,3,4].sum
# undefined method `sum' for [1, 2, 3, 4]:Array (NoMethodError)
class Array
def sum
sum = 0
self.each do |e|
sum += e
end
sum
end
end
[1,2,3,4].sum # 10
# Monkey Patch a Ruby Class METHOD with alias:
f = FriendClass.new
f.my_greeting("Fred")
# Hello, Fred.
class FriendClass
alias old_my_greeting my_greeting
def my_greeting(name)
puts "I used to say '#{old_my_greeting(name)}'.
puts "Now I say, whats up, #{name}?"
end
end
f.my_greeting("Fred")
# I used to say 'Hello, Fred.'.
# Now I say, what's up, Fred?
# By using alias, we can safely redefine my_greeting and still have access to the original version through old_my_greeting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment