Created
August 25, 2011 14:15
-
-
Save isaacsanders/1170768 to your computer and use it in GitHub Desktop.
Keeping it Classy
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
# Foo is a constant that | |
Foo = Class.new | |
# We can define a superclass as an argument of the Class#new method, | |
# but the default is Object, and we are fine with that. | |
#=> Foo | |
Foo.class_eval do | |
def bar | |
:baz | |
end | |
end | |
#=> nil | |
Foo.instance_eval do | |
def baz | |
:bar | |
end | |
end | |
#=> nil | |
Foo.bar | |
Foo.new.baz | |
#=> Both raise an error | |
Foo.baz | |
Foo.new.bar | |
#=> :bar and :baz, respectively | |
# This is a little different, but still somewhat familiar looking. |
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
class Foo | |
def bar | |
:baz | |
end | |
def self.baz | |
:bar | |
end | |
end | |
#=> nil | |
foo = Foo.new | |
# returns a new Foo object, foo | |
foo.bar | |
#=> :baz | |
# This is how we normally declare our classes. | |
# I think that this is because this is how we teach | |
# other languages, so teaching Ruby this way is just easier. | |
# However, there are other ways we can do things. |
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
foo = Class.new | |
# returns an instance of Class | |
foo.new | |
# returns an instance of the instance of Class. | |
foo.new.class | |
# returns our instance of class. | |
foo.class_eval do | |
def bar | |
:baz | |
end | |
end | |
#=> nil | |
foo.new.bar | |
#=> :baz | |
foo = 0 | |
foo.new.bar | |
#=> raises an error, it's not a class anymore, dummy! | |
# Here we are just using a variable that we can overwrite to define our class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment