Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Method object for a method?

Tags:

ruby

I'm trying to extend the Method class along the lines of:

irb(main):008:0> class A
irb(main):009:1> def a
irb(main):010:2> puts "blah"
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> class Method
irb(main):014:1> def aa
irb(main):015:2> p "hi"
irb(main):016:2> end
irb(main):017:1> end
=> nil
irb(main):018:0> f = A.new
=> #<A:0x54ed4>
irb(main):019:0> A.a
NoMethodError: undefined method `a' for A:Class
    from (irb):19
    from :0
irb(main):020:0> f.a
blah
=> nil
irb(main):027:0> f.a.aa
blah
NoMethodError: undefined method `aa' for nil:NilClass
    from (irb):27
    from :0

As expected, when I f.a.aa, the .aa is being executed on the return value of f.a. How do I gain access to the Method object which represents f.a?

like image 435
Jim Keener Avatar asked Feb 09 '09 18:02

Jim Keener


People also ask

How do you access methods of objects?

Access Methods With an Object 1) We created a custom Main class with the class keyword. 2) We created the fullThrottle() and speed() methods in the Main class. 3) The fullThrottle() method and the speed() method will print out some text, when they are called.

How do you call a method object?

Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.

What is a method object?

A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of state data and behavior; these compose an interface, which specifies how the object may be utilized by any of its various consumers. A method is a behavior of an object parametrized by a consumer.


1 Answers

With the method method... =)

f.method(:a).aa
like image 147
Ola Bini Avatar answered Sep 24 '22 08:09

Ola Bini