<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
02
%q{Singleton Classes}
cheatsheet = Object.new

# All objects have a singleton class
cheatsheet.singleton_class
=> #<Class:#<Object:0x007fe9ab2264f0>>

# Alternate syntax
class << cheatsheet
self
end == cheatsheet.singleton_class
=> true

# Singleton classes are specific
# to the instance
obj = Object.new
cheatsheet.singleton_class == obj.singleton_class
=> false

# Define method directly on object
def cheatsheet.publisher
'Degica'
end

# Alternate syntax
class << cheatsheet
def publisher
'Degica'
end
end

# Methods is on singleton class
cheatsheet.method(:publisher).owner ==
cheatsheet.singleton_class
=> true

cheatsheet.respond_to? :publisher
=> true
obj.respond_to? :publisher
=> false

# Also works for classes!
def Object.meow
'meow'
end

# Typical syntax (class methods)
class Object
class << self
def meow
'meow'
end
end
end
Object.respond_to? :meow
=> true

# But method is not available on instance
cheatsheet.respond_to? :meow
=> false

class Book
def title
@title
end
end

# Get ancestors of a singleton class
# to see where its methods come from
Book.new.singleton_class.ancestors
=> [#<Class:#<Book:0x007f96ee1a2340>>,
Book,
Object,
Kernel,
BasicObject]

# Get an unbound (selfless) method
unbound = Book.instance_method(:title)

# Bind the method to use it
r = Book.new
r.instance_variable_set(:@title, 'A')
unbound.bind(r).call
=> 'A'

# Same as a method obtained by #method
r.method(:title) == unbound.bind(r)
=> true

# You can define a method on the
# singleton class of a class
def Book.page_material
'paper'
end

# Child classes will inherit it
class Booklet < Book
end

Booklet.page_material
=> "paper"
02
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>