Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 518
Amit Suroliya Avatar asked May 22 '15 16:05

Amit Suroliya


People also ask

What is Ruby send?

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.

What is public send?

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.

What is a method in Ruby?

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.

How do you call a method in Ruby?

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.


1 Answers

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) 
like image 55
Casper Avatar answered Sep 28 '22 00:09

Casper