谁能帮我看一下这个ruby类

Python017

谁能帮我看一下这个ruby类,第1张

private 方法不能有接受方

即通过 对象名.方法名 来调用私有方法是行不通的,不过可以在Test类或其子类的方法中调用该私有方法(直接写方法名才行)

如:

class Test

def method1#默认为公有方法

end

protected #保护方法

def method2

end

private #私有方法

def method3

end

end

class Mytest <Test

def test_private()

method3 #正确,可以访问父类对象的私有方法

end

end

class OtherTest(注意它不是Test的子类)

def test_protected(arg) #arg是Test类的对象

arg.method2 #正确,保护方法可以把Test类或Test类的子类作为接受方

end

obg1 = Test.new

obg2 = Mytest.new

obg3 = OtherTest.new

obg3.test_protected(obg1) #正确

obg3.test_protected(obg2) #正确

在 ruby 中,{|args| statements} 叫做 匿名函数,就是没有名字的小型函数。然后 each_byte 是一个方法,它接收一个可调用对象。

有时候左花括号可以用 do 代替,有花括号用 end 代替,就是

do |args|

statements

end

这种形式。