Method Alias ​​for Single Object

I am trying to define a singleton alias. How in:

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

I am sure that I can pass the method object as the second parameter.

I would not want to do this

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

I want the String#+ method not to use it. The emphasis is on aliases, but sending the actual method object as the second parameter will also be cool.

+5
source share
1 answer

Singleton methods are contained in this singleton class object:

 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 basically does something like this:

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

Source: https://habr.com/ru/post/1258210/


All Articles