Created
January 11, 2011 05:25
-
-
Save hopsoft/774061 to your computer and use it in GitHub Desktop.
Open Classes - Illustrates how to re-open a class in Ruby
This file contains 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
# define original class | |
class Example | |
def say_hello | |
puts "hello" | |
end | |
end | |
# re-open the class | |
class Example | |
# add new functionality | |
def do_stuff | |
puts "doing stuff" | |
end | |
end | |
# usage | |
Example.new.say_hello # => hello | |
Example.new.do_stuff # => doing stuff | |
# other ways to reopen the class | |
# open the instance of the class definition | |
Example.instance_eval do | |
end | |
# open the eigenclass | |
# you need to understand Ruby's object model | |
# to fully understand what the eigenclass is | |
class << Example | |
end | |
# syntactic sugar for class << Example | |
Example.class_eval do | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment