Last active
December 12, 2015 02:48
-
-
Save xaviervia/4701127 to your computer and use it in GitHub Desktop.
Fast way to create a class dynamically and add methods to it.
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
# Creating the class | |
class_reference = Object.const_set 'Shalalala', Class.new(Array) # Array will be setted as the superclass for Shalalala. Neat, ha? | |
# defining a method | |
class_reference.class_eval do | |
define_method :my_method, proc { puts 'hello' } | |
end | |
# See for yourself | |
instance = class_reference.new | |
instance.my_method # => 'hello' | |
# Most interestingly, the class was defined in the constant so can be referenced anywhere | |
Shalalala.new.my_method # => 'hello' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment