Last active
August 29, 2015 14:25
-
-
Save jasonleonhard/6d372a18acd0d98be047 to your computer and use it in GitHub Desktop.
MONKEY PATCHING: Class and Method examples
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
# 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