开发者

Protected and Private methods

开发者 https://www.devze.com 2023-02-15 08:01 出处:网络
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

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

 开发者_StackOverflow 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.


protected methods (or atributes) can only be used by the classes that inherit the class with protected methods (or atributes).

a      d
 \      \
  b      e
   \
    c

If the class a have a protected method, this can be used by b and c, but can't be used by d or e. Note: Ascii art diagram for inherit in ruby classes.

class A   
   public 
   def f obj
      obj.c
   end
   def g obj
      obj.b
   end
   def call_b
     b
   end

   private

   def b
      puts "Hi!_b"
   end


   protected
   def c
      puts "Hi!_c"
   end
end

a = A.new
b = A.new

a.f(b) # Hi!_c
a.g(b) # inj.rb:7:in `g': private method `b' called for #<A:0xb76df4cc> (NoMethodError)
a.call_b # Hi!_b  

In this case, the method f can 'see' the protected method because its of the same class (or an inherited one), but the private method encapsulate(hides) the 'b' method of all the cases, except if this is called inside of his class (by another accesible method (in this case, the method call_b)).

0

精彩评论

暂无评论...
验证码 换一张
取 消