Ruby中的类

初识ruby中的类

只需要简单的两行

class Point
end

如果我们此时实例化一个类那么他会有一些自省(introspection)的方法

p = Point.new

p.methodes(false) # 可以看到他自己定义的方法
Point.ancestors # 可以看到他的祖先
p.methods #列出所有的方法

class Point
    def initialize(x, y)
        # @x instance variable
        # @@x class variable
        # $x global variable
        # x local variable
        @x, @y = x, y
    end
end

我们丰富了一下这个类

# 这是我们实例化一个类的话
p = Point.new
# 接着我们想要拿其中的的变量的话
p.x 
# 会报错
undefined method 'x' 

在ruby中如果要访问或者修改一个变量那么一定要定义getter,setter方法。

attr_accessor :x
attr_reader :y

方法中的变量

class Point
    def initialize(x, y)
        # @x instance variable
        # @@x class variable
        # $x global variable
        # x local variable
        @x, @y = x, y
    end
    def first_quadrant?
        x > 0 && y >0
    end
end

看到这段代码感觉是不是有点问题呢 我们在first_qudrant?这个方法中没有用到@x直接使用了x
因为这个方法是一个实例方法,那么里面的变量就会默认加上selfself指的就是实例变量本身,所以就是@x

类中的常量

如果ruby中定义了一个常量如下

class Point
    ORIGIN = 20
end

我们要拿到这个值的话那么
Point::ORIGIN

原文地址:https://www.cnblogs.com/Stay-J/p/9601516.html