public.class => Class irb(main):002:0> private.class => Class ...">

"public" and "private" are classes, but "protected" are not?

irb(main):001:0> public.class
=> Class
irb(main):002:0> private.class
=> Class

I am surprised that the class publicis equal Class, the same for private, let me continue my test:

irb(main):003:0> protected.class
NameError: undefined local variable or method `protected' for main:Object
        from (irb):3
        from D:/Ruby2.0.0/bin/irb:12:in `<main>'

Er, now I'm more confused. So my questions are:

  • Are classes publicand really private?
  • Why protectedis it different?
+4
source share
2 answers

The answer to question 1 is not, publicand privateare not classes, they are module methods, as well protected. They all return self, although in your example this is an instance Class.

2.1.2 :006 > defined? public
 => "method" 

, protected -, . , - (main) .

, :

class Foo
  puts public
  puts private
  puts protected
end

, protected:

Foo
Foo
Foo
+3

, , , .

protected, protected, , private . private . private .

, 2 (obj1 obj2), Class. obj1 protected obj2, , obj1 private obj2, obj2.

, , , / , -.

, , - .

0

All Articles