Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Keeping it Classy
# 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.
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.
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