O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required