Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Created September 23, 2014 17:55
Show Gist options
  • Save justincampbell/f53fb32a3f48ef125ed1 to your computer and use it in GitHub Desktop.
Save justincampbell/f53fb32a3f48ef125ed1 to your computer and use it in GitHub Desktop.
class Cat
def make_sound
'meow'
end
end
# Anonymous classes assigned to a constant get the name of that constant
klass = Class.new do
def make_sound
'woof'
end
end
Dog = klass
Wolf = klass
Cat # => Cat
Dog # => Dog
Wolf # => Dog
# Duping/cloning an instance of a class before assigning allows you to assign
# it to multiple constant names
klass = Class.new do
def make_sound
'woof'
end
end
Dog = klass.dup
Wolf = klass.dup
Cat # => Cat
Dog # => Dog
Wolf # => Wolf
Cat.new.make_sound # => "meow"
Dog.new.make_sound # => "woof"
Wolf.new.make_sound # => "woof"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment