is it possible to turn a private method into a public one?

T

Thomas B.

Lex said:
hey guys !

could a private/protected method be turned into a public one ?

class K
private
def m
end
# now m is private
public :m
# and now it is public
end

TPR.
 
X

Xavier Noria

could a private/protected method be turned into a public one ?

Sure.

On the one hand you can circumvect access control with Object#send:

object.send:)method_name_even_if_private, ...)

And yes, you indeed can change the visibility:

class C
private
def foo
puts "it works"
end
end

c = C.new
begin
c.foo
rescue
puts $!
C.send:)public, :foo)
c.foo
end
# =>
# private method `foo' called for #<C:0x22013c>
# it works

That public is similar to the private call in C, only done out of the
class and via #send because it is private.

It is interesting to note that we've been able to call the method on
an object that was created when #foo was private, as the raised
exception proves. That's because method calls are resolved on a per
call basis due to the dynamic nature of Ruby.
 

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
474,279
Messages
2,571,387
Members
48,092
Latest member
Aurora0551

Latest Threads

Top