call a protected method on an instance of a class in ruby

To call a protected method on an instance of a class in Ruby, you can use the send method that's built into Ruby.

Assuming you have a class named MyClass with a protected method named my_protected_method, and you have an instance of that class named my_instance, you can call the method like this:

main.rb
my_instance.send(:my_protected_method)
39 chars
2 lines

The send method takes a symbol representing the method name as its argument. This can be any method, including protected and private methods. By using send, we bypass the protection mechanisms that prevent outside code from calling those methods. However, this technique should be used with care, as it allows you to subvert the encapsulation provided by the class's implementation.

gistlibby LogSnag