Protected and Private methods

Posted by cabaret on Stack Overflow See other posts from Stack Overflow or by cabaret
Published on 2011-03-06T21:19:55Z Indexed on 2012/03/27 23:30 UTC
Read the original article Hit count: 254

I'm reading through Beginning Ruby and I'm stuck at the part about private and protected methods. This is a newbie question, I know. I searched through SO for a bit but I couldn't manage to find a clear and newbie-friendly explanation of the difference between private and protected methods.

The book gives two examples, the first one for private methods:

class Person
  def initialize(name)
    set_name(name)
  end

  def name
    @first_name + ' ' + @last_name
  end

  private
  def set_name(name)
    first_name, last_name = name.split(/\s+/)
    set_first_name(first_name)
    set_last_name(last_name)
  end

  def set_first_name(name)
    @first_name = name
  end
  def set_last_name(name)
    @last_name = name
  end
end

In this case, if I try

 p = Person.new("Fred Bloggs") 
 p.set_last_name("Smith")

It will tell me that I can't use the set_last_name method, because it's private. All good till there.

However, in the other example, they define an age method as protected and when I do

 fred = Person.new(34)
 chris = Person.new(25)
 puts chris.age_difference_with(fred)
 puts chris.age

It gives an error:

:20: protected method 'age' called for #<Person:0x1e5f28 @age=25> (NoMethodError)

I honestly fail to see the difference between the private and protected methods, it sounds the same to me. Could someone provide me with a clear explanation so I'll never get confused about this again?

I'll provide the code for the second example if necessary.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about methods