I need to make some instance methods private after registering that object in another object.
I don't want to freeze the object because it must remain editable, only with less functionality. And I don't want to undef the methods since they are used internally.
What I need is something like:
class MyClass
def my_method
puts "Hello"
end
end
a = MyClass.new
b = MyClass.new
a.my_method #=> "Hello"
a.private_instance_method(:my_method)
a.my_method #=> NoMethodError
b.my_method #=> "Hello"
Any ideas?
You can call method private
on the method name anytime to make it private:
>> class A
>> def m
>> puts 'hello'
>> end
>> end
=> nil
>> a = A.new
=> #<A:0x527e90>
>> a.m
hello
=> nil
>> class A
>> private :m
>> end
=> A
>> a.m
NoMethodError: private method `m' called for #<A:0x527e90>
from (irb):227
from /usr/local/bin/irb19:12:in `<main>'
or, from outside the class:
A.send :private, :m
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With