[ruby] Ruby中的class和object

144 阅读1分钟

定义Class

Ruby中定义类的语法结构:

class ClassName

  attr_accessor :instance_property // 为实例属性instance_property提供getter/setter

  // initialize方法定义了执行ClassName.new("xx")时的行为
  def initialize(whatever_name)
    @instance_property = whateve_name
  end

  private // 下面定义的方法为私有方法,外面访问不到

    def private_method
      // 省略....
    end
end

Ruby中类名采用CamelCase,变量命名、方法命名采用snake_case。

继承

对Ruby中的任何对象应用class方法会返回对应的类型,应用superclass方法返回父类的类型,如:"any string".class 返回String。"any string".class.superclass返回Object。"any string".class.superclass.superclass返回BaseObject。string".class.superclass.superclass.superclass返回nil。

类继承通过 < 符号实现,如:

class ClassName < SuperClass

  attr_accessor :argument_two

  def initialize(arg_1, arg_2)
    super(arg_1) // 将参数传递给父类
    @argument_two = arg_2
  end
end

方法重写

Ruby中子类重写父类方法,只需要使用相同的方法签名即可。运行时,Ruby知道执行子类的重写版本。

Monkey Patching

指运行时通过改变class对现有的代码进行修改或者扩充功能。比如,我们想在String类中添加新的方法palindrome?,用来判断当前字符串是否是回文串,实现如下:

class String
  def palindrome?
    self.downcase == self.downcase.reverse
  end
end

上面的实现将palindrome?方法添加到了String类中,扩充了Ruby中的String类的功能。我们可以直接对字符串应用这个方法,如:"abc".palindrome? 返回false。"aba".palindrome?返回true。

Monkey-patching虽然强大,但要慎用。

Module

又名mixin,可以将通用的功能集中起来,在需要的类中通过include关键字引入。举例:不仅字符串可以判断是否为回文,整数也可以判断是否为回文,我们可以如下定义Palindrome module,并在String和Integer类中引入。这样,String和Integer实例均具有判断回文的函数。

module Palindrome
  def palindrome?
    processed_content == processed_content.reverse
  end

  private
  
    def processed_content
      self.to_s.downcase
    end
end

class String
  include Palindrome
end

class Integer
  include Palindrome
end

如下应用:
"Racecar".palindrome? 返回true
12321.panlindrome? 返回true

Content mainly excerpted from 「Learn enough Ruby to be dangerous: write programs, pushlish gems and write Sinatra web apps with Ruby」 by Michael Hartl