Skip to content

Instantly share code, notes, and snippets.

@sandheepg
Created March 8, 2017 07:59
Show Gist options
  • Save sandheepg/e3745b422b380b48df31e68c7713e8fd to your computer and use it in GitHub Desktop.
Save sandheepg/e3745b422b380b48df31e68c7713e8fd to your computer and use it in GitHub Desktop.
Using send method in ruby

In Ruby, send is often introduced as a way to show how everything is an object

1.send(:+, 1)  ## -> 2

It can also be used to call private or protected methods from outside a given class as explained below.

class Myclass
  def method_one
    puts "instance method called."
  end
  
  private
  
  def private_one
    puts "private method called." 
  end
end

my_obj = Myclass.new
my_obj.method_one  #=> "instance method called."    
my_obj.private_one   #=> NoMethodError: private method `private_one' called for #<Myclass:0xb739d9bc>
my_obj.send(:private_one)  #=> "private method called."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment