I am very curious to know what the difference is between send
and public_send
. E.g.:
class Klass def hello(*args) "Hello " + args.join(' ') end end k = Klass.new k.send :hello, "gentle", "readers" #=> "Hello gentle readers" k.public_send :hello, "gentle", "readers" #=> "Hello gentle readers"
Can someone please explain the difference?
Ruby Language Metaprogramming send() method send() is used to pass message to object . send() is an instance method of the Object class. The first argument in send() is the message that you're sending to the object - that is, the name of a method. It could be string or symbol but symbols are preferred.
public_send(*args) public. Invokes the method identified by symbol, passing it any arguments specified. Unlike send, public_send calls public methods only. When the method is identified by a string, the string is converted to a symbol.
A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function. A method may be defined as a part of a class or separately.
We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.
http://apidock.com/ruby/Object/public_send
Unlike send, public_send calls public methods only.
Example:
class Klass private def private_method puts "Hello" end end k = Klass.new k.send(:private_method) => "Hello" k.public_send(:private_method) => `public_send': private method `private_method' called for #<Klass:0x007f5fd7159a80> (NoMethodError)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With