public methods
public methods 可以被所有人访问,他没有访问控制, note: 方法默认是public的,(除了initialize方法,它总是私有的)
protected methods
protected methods 只能被(定义方法的类或者它的子类)的对象调用,并且 访问只能在(定义方法的类或者它的子类)进行。
private methods
private methods 不能被明确的(explicit)接收者(receiver)调用,它的接收者总是当前对象(self),这说明私有方法只能在当前对象的上下文环境被调用,你不能调用其他对象的私有方法
#第一种写法
class MyClass
def method_1 #default public
end
private #下面的方法都是私有的
def method_2
end
def method_3
end
protected #下面的方法都是保护方法
def method_4
end
end
#第二种写法
class MyClass
def method_1
end
def method_2
end
def method_3
end
public :method_2
protect :method_1
private :method_3
end
example
class Account
attr_accessor :balance
def initialize(balance)
@balance = balance
end
end
class Transaction
def initialize(outer,incomer)
@outer = outer
@incomer = incomer
end
def traning(count)
out(count)
income(count)
end
private
def out(count)
@outer.balance -= count
end
def income(count)
@incomer.balance += count
end
end
account_1 = Account.new(100)
account_2 = Account.new(200)
trans = Transaction.new(account_1,account_2)
trans.traning(50)
p "account_1: #{account_1.balance}, account_2: #{account_2.balance} "
#=> account_1: 50, account_2: 250