ruby access control(public,protected,private)

本文详细介绍了Ruby中的访问控制概念,包括public、protected和private方法的区别与使用方式,并通过具体示例展示了如何在类中声明不同访问级别的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值