Skip to content

Instantly share code, notes, and snippets.

@isaacsanders
Created August 25, 2011 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacsanders/1170768 to your computer and use it in GitHub Desktop.
Save isaacsanders/1170768 to your computer and use it in GitHub Desktop.
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