What Is the Difference Between Ruby Send and Ruby Public_Send Method?

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

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

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest