Fil*_*eca 5 ruby access-specifier
在将该对象注册到另一个对象后,我需要将一些实例方法设为私有.
我不想冻结对象,因为它必须保持可编辑状态,但功能较少.而且我不想取消这些方法,因为它们是在内部使用的.
我需要的是:
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"
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
您可以随时调用方法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>'
Run Code Online (Sandbox Code Playgroud)
或者,从课外:
A.send :private, :m
Run Code Online (Sandbox Code Playgroud)
class A
def test
puts "test"
end
def test2
test
end
end
a = A.new
class << a
private :test
end
a.test2 # works
a.test # error: private method
Run Code Online (Sandbox Code Playgroud)
什么是公共的,什么是私有的,是按类划分的。但每个对象都可以有自己的类:
class Foo
private
def private_except_to_bar
puts "foo"
end
end
class Bar
def initialize(foo)
@foo = foo.dup
class << @foo
public :private_except_to_bar
end
@foo.private_except_to_bar
end
end
foo = Foo.new
Bar.new(foo) # => "foo"
foo.private_except_to_bar
# => private method `private_except_to_bar' called for #<Foo:0xb7b7e550> (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
但是哎呀。考虑以下替代方案:
归档时间: |
|
查看次数: |
5024 次 |
最近记录: |