Created
March 17, 2012 14:03
-
-
Save clm-a/2059540 to your computer and use it in GitHub Desktop.
Some ruby samples playing with classes
This file contains 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
# 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