Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of private, protected, and public

Within a Ruby class definition, what is the scopes of the private keyword in the following scenarios:

class Foo

  def bar_public
    puts "public"
  end

private
  def bar_private
    puts "private"
  end

  def bar_public_2
    puts "another public"
  end

end

Does private only act on bar_private? or on bar_public_2 as well?

like image 735
pseudosudo Avatar asked Jun 30 '11 18:06

pseudosudo


People also ask

What is the scope of private?

A member that is private can be accessed (without any or on any instance of the class) from within code written inside the class definition and all out-of-class definitions for members of the class.

What is the scope of a private class?

The scope of the private modifier lies with in the class. Members that are declared private cannot be accessed outside the class. Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

What is the difference between public and private methods?

A public method can be invoked from anywhere—there are no restrictions on its use. A private method is internal to the implementation of a class, and it can only be called by other instance methods of the class (or, as we'll see later, its subclasses).

What is public/private and protected class?

PHP - Access Modifierspublic - the property or method can be accessed from everywhere. This is default. protected - the property or method can be accessed within the class and by classes derived from that class. private - the property or method can ONLY be accessed within the class.


2 Answers

In your case both bar_private and bar_public_2 are private.

That is because both methods are "within scope" of the private keyword.

> f = Foo.new
#<Foo:0xf1c770>
> Foo.new.bar_private
NoMethodError: private method 'bar_private' called for #<Foo:0xf1c770>
> Foo.new.bar_public_2
NoMethodError: private method 'bar_public_2' called for #<Foo:0xf1c770>

Either way, the best way to answer you question is to open IRB and try it out ;-)

like image 127
Jeremy Avatar answered Oct 20 '22 08:10

Jeremy


If you find it weird that private is affecting both bar_private and bar_public_2, then rather than use private, use private :bar_private after defining bar_private.

like image 30
Andrew Grimm Avatar answered Oct 20 '22 07:10

Andrew Grimm