private class methods- functionality or shortcoming?

A

amit saxena

[Note: parts of this message were removed to make it a legal post.]

I just switched to Ruby and came across it.
If we have to make a class method private then we should write it as:

class Abc
   
    class<<self
        private
        def fun
            p "hello"
        end
    end
   
end

But if we write as:

class Abc
   
    private
    def self.fun
        p "hello"
    end

end

then the class method is not private but behaves as public.

So, is it a carefully designed functionality? If so, then what is the thinking behind it?
OR any other reasons behind it?
Somebody told me that ruby encourages to define class methods the first way.
But I think that if you are giving more than one methods to do a thing, then all should function the same way.

Thanks and Regards,
Amit
 
S

Stefano Crocco

I just switched to Ruby and came across it.
If we have to make a class method private then we should write it as:

class Abc
   
    class<<self
        private
        def fun
            p "hello"
        end
    end
   
end

But if we write as:

class Abc
   
    private
    def self.fun
        p "hello"
    end

end

then the class method is not private but behaves as public.

So, is it a carefully designed functionality? If so, then what is the
thinking behind it? OR any other reasons behind it?
Somebody told me that ruby encourages to define class methods the first
way. But I think that if you are giving more than one methods to do a
thing, then all should function the same way.

Thanks and Regards,
Amit

The Module#private method only works for instance methods, not for class
method. To make a class method private, you should use the
Module#private_class_method method. Note that, unlike private,
private_class_method only accepts one argument, so that you want to make more
than one method private, you should call it multiple times.

So, the correct method to make the method private using the second form is:

class Abc

def self.fun
p "hello"
end
private_class_method :fun

end

I hope this helps

Stefano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top