Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #2578

private vs. protected question

From Kaye Ng <sbstn26@yahoo.com>
Newsgroups comp.lang.ruby
Subject private vs. protected question
Date 2011-04-09 05:24 -0500
Organization Service de news de lacave.net
Message-ID <bd7050a7923405894788738f2712f45b@ruby-forum.com> (permalink)

Show all headers | View raw


From a book I'm reading:
------------------------------------------------------------------------
class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

  protected :age
end

fred = Person.new(34)
chris = Person.new(25)
puts chris.age_difference_with(fred)
puts chris.age
-------------------------------------------------------------------------
results in:

9
:20: protected method 'age' called for #<Person:0x1e5f28 @age=25>
(NoMethodError)
------------------------------------------------------------------------
The first 'puts' line printed '9' on the screen, while the second
resulted
in error.  This is because, like 'private', I cannot use a specific
receiver to call a protected method, correct?

Now I'm going to replace 'protected' with 'private' (and omit the last
line (puts chris.age) ). This would result in:

-------------------------------------------------------------------------
H:/Ruby/Practice/six.rb:9:in `age_difference_with': private method `age'
called for
#<Person:0x19ccf68 @age=25> (NoMethodError)from
H:/Ruby/Practice/six.rb:16:in `<main>'
------------------------------------------------------------------------

Explanation from the book:
" if
age were made private, the preceding example would fail because
other_person.age would
be invalid. That’s because private makes methods accessible only by
methods of a specific
object."

From the statement, "...because private makes methods accessible only by
methods of a specific
object.", I'm assuming that it also means 'accessible only by methods of
a single and CURRENT object', and that current object is 'chris', not
'fred', and that is why it resulted in error.

Am I wrong??
Help please! Thank you!!

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | NextNext in thread | Find similar | Unroll thread


Thread

private vs. protected question Kaye Ng <sbstn26@yahoo.com> - 2011-04-09 05:24 -0500
  Re: private vs. protected question 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-09 14:35 -0500
    Re: private vs. protected question 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-09 16:37 -0500
  Re: private vs. protected question 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-09 17:11 -0500

csiph-web