Search code examples
rubymethodssend

What is the point of using "send" instead of a normal method call?


as far as I understand 'send' method, this

some_object.some_method("im an argument")

is same as this

some_object.send :some_method, "im an argument"

So what is the point using 'send' method?


Solution

  • It can come in handy if you don't know in advance the name of the method, when you're doing metaprogramming for example, you can have the name of the method in a variable and pass it to the send method.

    It can also be used to call private methods, although this particular usage is not considered to be a good practice by most Ruby developers.

    class Test
      private
      def my_private_method
        puts "Yay"
      end
    end
    
    t = Test.new
    
    t.my_private_method # Error
    
    t.send :my_private_method #Ok
    

    You can use public_send though to only be able to call public methods.