DriversManual: Metaprogramming Ruby Chapter 2 Part 1


The Object Model


Contents


class

Open Classes


class Foo
  def one_method
    puts 'one'
  end
end

class Foo
  def two_method
    puts 'two'
  end
end

foo-instance = Foo.new

foo-instance.one_method # => 'one'
foo-instance.two_method # => 'two'

Editing Standard Library Objects


class String
  def word_characters
    gsub(/[^\w]+/, '')
  end
end

"asdf1234##".word_characters # => 'asdf1234'

Problem with Open Classes


class Array
  def replace(...)
  end
end

What’s an object?

obj = MyObject.new

figure one: object instance variables and method locations

Classes

Modules

Classes as Objects

Classes as Objects (diagram)

figure two: classes are objects

Constants

Structure like a File System


module M
  class C
    X = 'a constant'
  end
  C::X # => "a constant"
end
M::C::X # => "a constant"

Objects and Classes Wrap-Up


Quiz Questions

Q: What is meant by 'Open' classes with ruby?
A: Classes can be changed on the fly
Q: What is Monkey Patching?
A: Changing Standard Class methods
Q: What parts of an instance is highlighted?
A: 1) instance variables, and 2) references to classes [that contain instance methods]
Q: What is the superclass of `Class`?
A: Module
Q: What are highlighted differences between Module and Class?
A: Class is an instance of Module. Classes have inheritance and instantiation Modules don't
Q: Compare instantiation vs child
A: Classes are children of their superclasses and instances of their class example: Class is an instance of Class and child of Module
Q: Class names were simply ________ in the text
A: constants
Q: How would you find a 'root' level constant 'Y'?
A: `::Y` the '::' acts like '~'
Q: With a File System metaphor, what is == to 'ls'?
A: the `Module#constants` method
Q: What is a Namespace?
A: a Module that exists to only be a container of constants
Q: What is an object?
A: instance vars + reference to its class
Q: What is a class?
A: instance of `Class` + instance methods + link to superclass