Ruby访问级别

示例

Ruby具有三个访问级别。他们是public,private和protected。

下面的方法private或protected关键字被定义为这样的。在这些方法之前的public方法是隐式方法。

公开方法

公共方法应描述所创建对象的行为。可以从创建的对象的范围之外调用这些方法。

class Cat
  def initialize(name)
    @name = name
  end

  def speak
    puts "I'm #{@name} and I'm 2 years old"
  end
  
  ...
end

new_cat = Cat.new("garfield")
#=> <Cat:0x2321868 @name="garfield">
 
new_cat.speak
#=> I'm garfield and I'm 2 years old

这些方法是公共红宝石方法,它们描述了初始化新猫的行为以及语音方法的行为。

public关键字是不必要的,但可以用于转义private或protected

def MyClass
  def first_public_method
  end

  private

  def private_method
  end

  public

  def second_public_method
  end
end

私有方法

私有方法不能从对象外部访问。它们在内部由对象使用。再次使用cat示例:

class Cat
  def initialize(name)
    @name = name
  end

  def speak
    age = calculate_cat_age # 这里我们称之为私有方法 
    puts "I'm #{@name} and I'm #{age} years old"
  end

  private
     def calculate_cat_age
       2 * 3 - 4 
     end
end

my_cat = Cat.new("Bilbo")
my_cat.speak #=> I'm Bilbo and I'm 2 years old
my_cat.calculate_cat_age #=> NoMethodError: private method `calculate_cat_age' called for #<Cat:0x2321868 @name="Bilbo">

如上例所示,新创建的Cat对象可以在calculate_cat_age内部访问该方法。我们将变量分配给age运行privatecalculate_cat_age方法的结果,该方法将猫的名称和年龄打印到控制台。

当我们尝试calculate_cat_age从my_cat对象外部调用该方法时,会收到一个NoMethodError因为它是私有的。得到它?

受保护的方法

受保护的方法与私有方法非常相似。不能像私有方法那样在对象实例之外访问它们。但是,使用selfruby方法,可以在相同类型的对象的上下文中调用受保护的方法。

class Cat
  def initialize(name, age)
    @name = name
    @age = age
  end

  def speak
    puts "I'm #{@name} and I'm #{@age} years old"
  end

  # 此==方法允许我们比较两个对象的自身年龄。 
  # 如果两只猫的年龄相同,则将它们视为相等。
  def ==(other)
    self.own_age== other.own_age
  end

  protected
     def own_age
        self.age
     end
end

cat1 = Cat.new("ricky", 2)
=> #<Cat:0x007fe2b8aa4a18 @name="ricky", @age=2>

cat2 = Cat.new("lucy", 4)
=> #<Cat:0x008gfb7aa6v67 @name="lucy", @age=4>

cat3 = Cat.new("felix", 2)
=> #<Cat:0x009frbaa8V76 @name="felix", @age=2>

您可以看到我们在cat类中添加了age参数,并使用名称和age创建了三个新的cat对象。我们将调用own_ageprotected方法来比较猫对象的年龄。

cat1 == cat2
=> false

cat1 == cat3
=> true

看一下,我们能够使用self.own_age保护方法检索cat1的年龄,并通过cat2.own_age在cat1内部进行调用将其与cat2的年龄进行比较。