ruby - How can I get a reference to a method? -


Is it possible to get the reference of an object's methods in Ruby (I have to know that it can be done without For example, consider the following code:

  class X def initialize @map = {} setup_map end personal def setup_map # @ map ["a"] = get a reference method # Get references to @map ["b"] = B method # @ map ["c"] End of C method, public DIF call (A) @ MAP ["A"] (A) Please get: If a> 10 @ map ["b"] (A) if a> 20 @ size ["c"] (A) if a 30 end DRF (AGR) is inserted with "A to # {arg} Was called "End DIF B (RGR))" B was called with the # {arg} "end DEP C (RGR) puts" C was called with # ARG "end" / Code>  

Is it possible to do this? I would like to avoid procs / lambdas because I want to be able to convert the behavior of A, B, C to subclassing.

you want object # method :

  ----------- -------------------------- --------------------- Object # method Obj.method (sym) = & gt; way ------------------------------------------------- ----------------------- OBJ shows the designated method as a receiver, returns an object object (or the name is being returned) . The method object acts as a closure in the object instance of obj, so the instance variables and their own value are available. Class Demo Deaf Initialization (n) @ EV = N & DEF Hello () "Hello, @ ove = # {@ iv}" & End = Kashmir. Demo.New (99) M = K Math (Hello) M.Clone # = & gt; "Hello, @ ove = 99" l = demo.new ('Fred') m = lmf ("hello") m.call # = & gt; "Hello, @ ow = Fred"  

Now your code goes:

  private def setup_map @map = {'a' => Method (: A), 'B' = & gt; Method (: B), 'C' = & gt; Method (: C)} # or more precisely # @ size = hash.nu {| _map, name | _map [name] = method (name.to_sym)} End public DRF call (RGR) @map ["a"] [AG] If RAG & gt; 10 @ size ["b"] [ag] if rage & gt; 20 @ size ["c"] [ag] if rag & gt; 30 end  

Comments