Search code examples
rubyaccess-specifier

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?


Solution

  • 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 ;-)