Ways to invoke a method in Ruby.

BharteeTechRubyOnRails
2 min readJun 7, 2023

--

Method Invocation using an Object:

The most common way to invoke a method is by using an object and the dot (.)

operator to call the method on that object.

 3.0.0 :051 > class Myclass
3.0.0 :052 > def my_method
3.0.0 :053 > puts "hello world!"
3.0.0 :054 > end
3.0.0 :055 > end
=> :my_method

3.0.0 :056 > obj = Myclass.new
=> #<Myclass:0x000055f694125d78>
3.0.0 :057 > obj.my_method
hello world!

In this example, the my_method is invoked on the obj object using the dot operator (obj.my_method).

Method Invocation using Self:

The self keyword in Ruby refers to the current object or instance within the context.

You can invoke a method using the self as an implicit receiver, especially when there is no ambiguity between local variables and methods.

It invokes the my_method using the self as an implicit receiver.

3.0.0 :058 > class Myclass
3.0.0 :059 > def my_method
3.0.0 :060 > puts "hi this is the my method"
3.0.0 :061 > end
3.0.0 :062 > def invoke_method
3.0.0 :063 > my_method
3.0.0 :064 > end
3.0.0 :065 > end
=> :invoke_method

3.0.0 :066 > obj = Myclass.new
=> #<Myclass:0x000055f694a10cf8>
3.0.0 :067 > obj.invoke_method
hi this is the my method
=> nil

Method Invocation using the send Method:

The send method in Ruby allows you to dynamically invoke a method by name, even if the method is private or protected.

3.0.0 :068 > class Myclass
3.0.0 :069 > private
3.0.0 :070 > def my_private_method
3.0.0 :071 > puts "hi this is the private method"
3.0.0 :072 > end
3.0.0 :073 > end
=> :my_private_method

3.0.0 :074 > obj = Myclass.new
=> #<Myclass:0x000055f694a01578>
3.0.0 :075 > obj.send(:my_private_method)
hi this is the private method
=> nil

Method Invocation using the public_send Method:

The public_send method in Ruby is similar to send, but it only allows the invocation of public methods.

This raises an error if the method is private or protected.

3.0.0 :088 > class Myclass
3.0.0 :089 > protected
3.0.0 :090 > def protected_method
3.0.0 :091 > puts "hi this is the protected method"
3.0.0 :092 > end
3.0.0 :093 > end
=> :protected_method

3.0.0 :094 > obj = Myclass.new
=> #<Myclass:0x000055f6946c8c80>
3.0.0 :095 > obj.public_send(:protected_methods)
=> [:protected_method, :my_obj_method]

--

--

BharteeTechRubyOnRails
BharteeTechRubyOnRails

Written by BharteeTechRubyOnRails

Ruby on Rails Developer || React Js || Rspec || Node Js

No responses yet