将方法别名为单个对象

Alias a method to a single object

我正在尝试定义一个单独的别名方法。 如:

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

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

我不想这样

name.define_singleton_method(:add_cuteness) { |val| self + val }

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

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

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

Object#define_singleton_method 基本上是这样的:

def define_singleton_method(name, &block)
  singleton_class.class_eval do
    define_method name, &block
  end
end