What I learned this week [3]

A. Ruby Metaprogramming: class_eval and instance_eval

class_eval creates an instance method
instance_eval creates a class method

B. Eigenclass

Integralist has a exceptional article about Eigenclass

Eigenclass methods is accessible by class <<. It is a class containing the singleton methods, and class methods.

First example: define a singleton method for an instance.

class Foo; end
foo = Foo.new
class << foo
  ...
end

Second example: define a singleton method for a class. Actually class Foo is an instance of class Class. And foo is an instance of class Foo

There are 4 ways to create a class method:

  1. Use self.method
  2. Use Class Open technique inside a class definition class << self
  3. Use Class Open technique outside of class definition class << Foo
  4. Use Foo.instance_eval
class Foo
def shout; end

def self.whistle; end

class << self
def sing; end
end
end

class << Foo
  def speak; end
end

Foo.instance_eval {
def talk; end
}
Foo.methods false
# [:speak, :talk, :sing]

Foo.instance_methods false
# [:shout]

And there are 2 ways to create an instance methods

class Bar
def fly; end
end

Bar.class_eval {
def soar; end
}

Bar.instance_methods false
# [:fly, :soar]

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s