How does "method definition" work semantically?

Story:

Here is what I understand about the object model (regarding my question below):

  • self always refers to the receiver in the current stack frame.
  • When you are at the top level and you say def someMethodan implicit receiver self, and you create a method that is in the anonymous class associated with self. This anonymous class sits just below Object( selfthis is an instance of the class Object), so when you call someMethod, Ruby "takes a step to the right," and it gets into the anonymous class, thus finding and calling your method.
  • This is similar to what happens when you define methods inside class definitions. If in the definition of the class you say: def self.classMethodyou create a method in an anonymous class that is only below the class Class. The methods of this class, existing "right" of the class currently defined, will not be visible to instances of the new class.

My question is:

How is the "method definition in the class"? (semantically)

Class objects should not be different from ordinary objects, right?

, , Class , - , . . ( Ruby , , -, Class.)

Ruby , , , Class, . , . , " " , Class?

, . , , def.

+4
1

"def something" ruby, . "" ( ). , "" :

class Foo

  # right now self is 'Foo'

  class << self
    # right now self is 'Class:Foo'
  end

  def self.bar
    # right now self is 'Foo'
  end

end

def Foo.buz
  # right now self is 'Foo'
end

obj = Foo.new

def obj.baz
  # right now self is 'Foo:0x007fe8a632fa78' (an instance)
end

- . - :

class Foo
end

class Bar < Foo
end

> Bar.ancestors
=> [Bar, Foo, Object, Kernel, BasicObject]

: mixins:

module Mixin
end
class Foo
  include Mixin
end

> Foo.ancestors
=> [Foo, Mixin, Object, Kernel, BasicObject]

, . ( ) , :

# bar.rb

module MixinA
  def something
    puts "MixinA"
    super
  end
end

module MixinB
  def something
    puts "MixinB"
  end
end

class Base
  def something
    puts "Base"
    super
  end
end

class Sub < Base
  include MixinB
  include MixinA
  def something
    puts "Sub"
    super
  end
end

obj = Sub.new
obj.something

Run:

$ ruby bar.rb
Sub
MixinA
MixinB

:

> Sub.ancestors
=> [Sub, MixinA, MixinB, Base, Object, Kernel, BasicObject]

, . , , method_missing. .

2009 :

+2

All Articles