O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dynamic Methods

Where you learn how to call and define methods dynamically, and you remove the duplicated code.

“When I was a young developer learning C++,” Bill says, “my mentors told me that when you call a method, you’re actually sending a message to an object. It took me a while to get used to that concept. If I’d been using Ruby back then, that notion of sending messages would have come more naturally to me.”

Calling Methods Dynamically

When you call a method, you usually do so using the standard dot notation:

methods/dynamic_call.rb
 
class​ MyClass
 
def​ my_method(my_arg)
 
my_arg * 2
 
end
 
end
 
 
obj = MyClass.new
 
obj.my_method(3) ​# => 6

You also have an alternative: call MyClass#my_method using Object#send in place of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required