Amit Suroliya
Amit Suroliya

Reputation: 1535

What is the difference between Ruby's send and public_send methods?

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"

Upvotes: 41

Views: 25240

Answers (1)

Casper
Casper

Reputation: 34308

Unlike send, public_send calls public methods only.

Source

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)

You may want to prefer #public_send over #send so as not to circumvent private/protected visibility.

Upvotes: 69

Related Questions