将方法别名为单个对象

l__*_*__l 5 ruby metaprogramming singleton-methods pointer-aliasing

我正在尝试定义单例别名方法.如:

name = 'Bob'
# I want something similar to this to work
name.define_singleton_method(:add_cuteness, :+)
name = name.add_cuteness 'by'
Run Code Online (Sandbox Code Playgroud)

我确信我可以将方法对象作为第二个参数传递.

我不想这样做

name.define_singleton_method(:add_cuteness) { |val| self + val }
Run Code Online (Sandbox Code Playgroud)

我想别名String#+方法不使用它.强调别名,但将实际方法对象作为第二个参数发送也很酷.

ndn*_*kov 6

单例方法包含在该对象的单例类中:

class Object
  def define_singleton_alias(new_name, old_name)
    singleton_class.class_eval do
      alias_method new_name, old_name
    end
  end
end

rob = 'Rob'
bob = 'Bob'
bob.define_singleton_alias :add_cuteness, :+

bob.add_cuteness 'by' # => "Bobby"
rob.add_cuteness 'by' # => NoMethodError
Run Code Online (Sandbox Code Playgroud)

Object#define_singleton_method 基本上做这样的事情:

def define_singleton_method(name, &block)
  singleton_class.class_eval do
    define_method name, &block
  end
end
Run Code Online (Sandbox Code Playgroud)