基础

对象是属于哪个类?

arg = []
str = "Hello Ruby"

p arg.class
#=> Array

p str.class
#=> String

判断对象是否属于某个类

arg = []

p ary.instance_of? Array
#=> true

p ary.instance_of? String
#=> false

根据继承关系,判断对象是否属于某个类

arg = []

p ary.is_a? Array
#=> true

p ary.is_a? String
#=> true

Ruby类的继承图

BasicObject
    Object
        Array
        String
        Hash
        Regexp
        IO
            File
        Dir
        Numeric
            Integer
                Fixnum
                Bignum
            Float
            Complex
            Rational
        Exception
        Time

初始化

相当于php的__construct()

class HelloWorld
    def initialize(name="Ruby")
        @name = name
    end

    def say
        @name
    end
end

hello = HelloWorld.new "Aaron"
p hello.say

存取器

在ruby中,从对象外部不能直接访问实例变量或者为实例变量赋值!

class HelloWorld
    def name
        @name
    end

    def name=(value)
        @name = value
    end
end

hello = HelloWorld.new
hello.name = "Aaron"
p hello.name

使用简便方法定义存取器

class HelloWorld
   attr_accessor :name
end

hello = HelloWorld.new
hello.name = "Aaron"
p hello.name
定义 意义
attr_reader :name 只读
attr_writer :name 只写
attr_accessor :name 读写

self

Ruby中,self相当于PHP$this,但是可以省略不写。