Ruby 2.0 define_method in the main

define_methodis a method Module.

In Ruby 2.0, it define_methodcan be used at the top level; it must not be inside a class or module.

define_method :kick do
  puts "method"
end

In Ruby 1.9, an object mainhas no method define_method.

define_method :kick
# => NoMethodError: undefined method `define_method' for main:Object

How does Ruby 2.0 implement this?

+4
source share
2 answers

I am also interested in learning about this feature and using irb to try a little. Please see:

% irb
2.0.0-p353 :001 > method(:define_method)
=> #<Method: main.define_method> 
2.0.0-p353 :002 > private_methods(false)
=> [:public, :private, :include, :using, :define_method, :irb_exit_org, :default_src_encoding, :irb_binding] 
2.0.0-p353 :003 > singleton_class.private_instance_methods(false)
=> [:public, :private, :include, :using, :define_method, :irb_exit_org] 

This shows that define_method is a private one-point method of the main object (self-level of the upper level).

+2
source

Based on uncutstone sleuthing, define_method () is not inherited by the main singleton class:

class <<self
  p private_instance_methods(false)
end

--output:--
[:public, :private, :include, :using, :define_method]

... , , . , , DEFS , , :

module A
  def greet
    puts 'hi'
  end
end

class Dog
  include A
end

p Dog.instance_methods(false)
p Dog.instance_methods.grep(/^g/)

--output:--
[]
[:greet]

, greet() . define_method() , define_method() . , , define_method() . , , ruby- :

class <<self
  def define_method(x, *y)
    #same code as in Module define method
  end
end
0

All Articles