In your example: in the initialize method you call the private method
set_name (with no error). That is calling the code from inside the class.
p =3D Person.new
p.set_name('foo')
raises an error. That is calling the code from outside the class.

Hope that helps.

--
gd

2011/3/30 Kaye Ng <sbstn26 / yahoo.com>

> This example demonstrates the use of 'private'
>
> 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 =3D name.split(/\s+/)
>    set_first_name(first_name)
>    set_last_name(last_name)
>  end
>  def set_first_name(name)
>    @first_name =3D name
>  end
>  def set_last_name(name)
>    @last_name =3D name
>  end
> end
>
> From the book:
> " private tells Ruby that any methods declared in this class from
> there on should be kept private. This means that only code within the
> object=92s methods can
> access those private methods, whereas code outside of the class cannot.
> For example, this code no longer works "
>
> p =3D Person.new("Fred Bloggs")
> p.set_last_name("Smith")
> _________________________________________________________________________=
_
> NoMethodError: private method 'set_last_name' called for
> #<Person:0x337b68
> @last_name=3D"Bloggs", @first_name=3D"Fred">
> _________________________________________________________________________=
__
>
> When the author says, "only code within the object=92s methods can
> access those private methods, whereas code outside of the class
> cannot.", what is the code in the example that can "access those private
> methods", and what is the "code outside of the class that cannot" ?
>
> That's it for now, more questions later.  Apologies to the author of
> this book, it's not you, it's me.  I'm a really slow learner.
>
> Thanks guys!
>
> --
> Posted via http://www.ruby-forum.com/.
>