Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

8.19. Controlling Access by Making Methods Private

Problem

You've refactored your code (or written it for the first time) and ended up a method that should be marked for internal use only. You want to prevent outside objects from calling such methods.

Solution

Use private as a statement before a method definition, and the method will not be callable from outside the class that defined it. This class defines an initializer, a public method, and a private method:

	class SecretNumber
	  def initialize
	    @secret = rand(20)
	  end
	  def hint
	    puts "The number is #{"not " if secret <= 10}greater than 10."
	  end 
private
	  def secret
	    @secret
	  end
	end

	s = SecretNumber.new
	s.secret
	# NoMethodError:  
private method 'secret' called for
	# #<SecretNumber:0xb7c2e83c @secret=19>

	s.hint
	# The number is greater than 10.

Unlike in many other programming languages, a private method in Ruby is accessible to subclasses of the class that defines it:

	class LessSecretNumber < SecretNumber
	  def hint
	    lower = secret-rand(10)-1
	    upper = secret+rand(10)+1
	    "The number is somewhere between #{lower} and #{upper}."
	  end
	end

	ls = LessSecretNumber.new
	ls.hint
	# => "The number is somewhere between -3 and 16."
	ls.hint
	# => "The number is somewhere between -1 and 15."
	ls.hint
	# => "The number is somewhere between -2 and 16."

Discussion

Like many parts of Ruby that look like special language features, Ruby's privacy keywords are actually methods. In this case, they're methods of Module. When you call private, protected, or public, the current ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required