Ruby 如何使用define_方法创建类方法?

Ruby 如何使用define_方法创建类方法?,ruby,metaprogramming,class-method,Ruby,Metaprogramming,Class Method,如果您试图以元编程方式创建类方法,这将非常有用: def self.create_methods(method_name) # To create instance methods: define_method method_name do ... end # To create class methods that refer to the args on create_methods: ??? end 我下面的答案来自:和,世卫组织也提

如果您试图以元编程方式创建类方法,这将非常有用:

def self.create_methods(method_name)
    # To create instance methods:
    define_method method_name do
      ...
    end

    # To create class methods that refer to the args on create_methods:
    ???
end
我下面的答案来自:和,世卫组织也提供了使这个更漂亮的方法

self.create_class_method(method_name)
  (class << self; self; end).instance_eval do
    define_method method_name do
      ...
    end
  end
end
self.create\u class\u方法(方法名称)

(class我更喜欢使用send调用define_方法,我还喜欢创建一个元类方法来访问元类:

class Object
  def metaclass
    class << self
      self
    end
  end
end

class MyClass
  # Defines MyClass.my_method
  self.metaclass.send(:define_method, :my_method) do
    ...
  end
end
类对象
def元类

类我认为在Ruby 1.9中可以做到:

class A
  define_singleton_method :loudly do |message|
    puts message.upcase
  end
end

A.loudly "my message"

# >> MY MESSAGE

这是Ruby 1.8+中最简单的方法:

class A
  class << self
    def method_name
      ...
    end
  end
end
A类

如果您想从关注点动态定义类方法,则要在Rails中使用的类:

module Concerns::Testable
  extend ActiveSupport::Concern

  included do 
    singleton_class.instance_eval do
      define_method(:test) do
        puts 'test'
      end
    end
  end
end

您也可以在不依赖define_方法的情况下执行类似操作:

A.class_eval do
  def self.class_method_name(param)
    puts param
  end
end

A.class_method_name("hello") # outputs "hello" and returns nil

谢谢!当然有很多方法可以让你自己变得更好。但是如果你正在开发一个开源插件,例如,我认为最好不要用
元类
阻塞名称空间,所以很高兴知道这个简单、独立的速记法。我决定使用我最初的答案。我的理解是使用send()如果在Ruby 1.9中退出,那么访问私有方法似乎不是一件好事情。另外,如果您定义了多个方法,那么对块进行实例求值会更干净。@Vincent Robert是否有任何链接可以解释元类方法的魔力?class Better(?)另一种方法可能是将东西放在一个模块中,然后让你的create|class|方法将模块扩展到类中???参见:另请参见
singleton|class.define|method
@Pyro只是为了澄清一下,你会去
singleton|class.define|u方法:大声做|消息|
等吗?我真的很喜欢这个。小,整洁,读起来很好,而且便于携带.当然,你可以问我在2013年使用ruby 1.8做了什么。。。
A.class_eval do
  def self.class_method_name(param)
    puts param
  end
end

A.class_method_name("hello") # outputs "hello" and returns nil