Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

What is the difference between ruby send and ruby public_send method?

Writer Olivia Zamora

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?

2

1 Answer

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)
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy