限制方法
限制方法定义
定义方法一
class AccTest
def pub
puts "pub is a public method."
end
#定义为public可以省略
public :pub
def priv
puts "priv is a private method."
end
private :priv
end
acc = AccTest.new
acc.pub
acc.priv
#=> 报错
定义方法二
class AccTest
public
def pub
puts "pub is a public method."
end
private
#以下方法均为private
def priv
puts "priv is a private method."
end
end
说明
定义 | 意义 |
---|---|
public | 以实例方法的形式向外公开改方法 |
private | 不能指定接收者(只能使用缺省接收者,所以无法从外部访问) |
protected | 在同一个类中时,可以将该方法作为实例方法调用 |
private
一定要记得定义为private
的不能指定接收者。
Ruby的private与PHP的并不一样,请注意!
1. 没有子类
class Parent
def priv
p "hello ruby"
end
private :priv
def test
priv
end
end
parent = Parent.new
parent.priv
#=> 报错
parent.test
#=> 成功
2. 有子类
class Parent
def priv
p "hello ruby"
end
private :priv
def test
priv
end
end
# < 在Ruby中就是继承,相当于php的extends
class Child < Parent
#这点和php不一样,在这里可以正常调用父类的private方法
def test2
priv
end
end
child = Child.new
child.priv
#=> 报错,不能指定接收者
child.test
#=> 成功
child.test2
#=> 成功
protected
与private相同的是,也不能指定接收者。但是在同一个类中,作为实例方法可以指定接收者。
这个更难理解了,和PHP完全不一样。
1. 没有子类
class Parent
def prot
p "hello ruby"
end
protected :prot
def test
prot
end
end
parent = Parent.new
parent.prot
#=> 报错,不能指定接收者
parent.test
#=> 成功
2. 有子类
class Parent
def prot
p "hello ruby"
end
protected :prot
def test
prot
end
end
class Child < Parent
def test2
prot
end
end
child = Child.new
child.prot
#=> 报错,不能指定接收者
child.test
#=> 成功
child.test2
#=> 成功
3. 特殊情况,在同一个类中,作为实例方法可以指定接收者
3.1 没有子类
class Parent
def prot
p "hello ruby"
end
protected :prot
def test other
#指定了接收者
other.prot
end
end
parent = Parent.new
parent2 = Parent.new
parent.prot
#=> 报错,不能指定接收者
parent.test parent2
#=> 成功,因为parent和parent2都是同一个类实例化的对象,可以调用
3.2 有子类
class Parent
def prot
p "hello ruby"
end
protected :prot
def test other
#指定了接收者
other.prot
end
end
class Child < Parent
end
parent = Parent.new
child = Child.new
parent.test child
#=> 成功,这样也是可以的
3.3 不是同一个类调用
class Parent
def prot
p "hello ruby"
end
protected :prot
def test other
#指定了接收者
other.prot
end
end
class Other
end
parent = Parent.new
other = Other.new
parent.test other
#=> 报错,这样当然就不行了,Other根本没有prot这个方法
Public
没啥好说的...一看就明白,随便调用