Skip to content

Instantly share code, notes, and snippets.

@clm-a
Created March 17, 2012 14:03
Show Gist options
  • Save clm-a/2059540 to your computer and use it in GitHub Desktop.
Save clm-a/2059540 to your computer and use it in GitHub Desktop.
Some ruby samples playing with classes
# Playing with classes and structs
MyClass = Class.new
p MyClass.class
# => Class
my_instance = MyClass.new
p my_instance
# => #<MyClass:0x10c67c840>
p my_instance.class
# => MyClass
# Structs
Car = Struct.new(:brand, :model)
p Car.class
# => Class
car1 = Car.new("Peugeot", "206")
p car1.brand
# => "Peugeot"
car2 = Car.new(Struct.new("Brand", :name).new("Peugeot"), "206")
p car2.brand
# => #<struct Struct::Brand name="Peugeot">
p car2.brand.name
# => "Peugeot"
require 'yaml'
p car2.to_yaml
=begin
--- !ruby/struct:Car
brand: !ruby/struct:Brand
name: Peugeot
model: "206"
=end
# Oh noes ! I have no references to the Brand class to create new instances :(
if car2.brand.class.respond_to? :name # ensure we got a brand-similar class by duck typing
my_lost_class = car2.brand.class
another_brand = my_lost_class.new("Porsche")
p another_brand.name
# => "Porsche"
p another_brand.class
# => Struct::Brand
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment