Ruby 类

编程/开发
445
0
0
2022-06-01

大写开头,使用new 关键字可以创建新的类

类属性 用@开头
color_string = String.new
color_string = "" #等同

color_array= Array.new
color_array = [] #等同

color_hash = Hash.new
color_hash = {} #等同

time = Time.new
puts time
class Person 
    def initialize(name)
        @name=name
    end 
    def say(word)
        puts "#{word}, #{@name}" 
    end
end
p1 = Person.new("hikari")
p2 = Person.new("lisa")
p1.say("konichiha")
p2.say("yoroshiku")

静态属性及方法

class Person 
    @@name="hikari" 
    def self.say
        puts @@name 
    end
end
Person.say

set get 约定

原始方法
class Person 
    def initialize(name)
        @name = name
        @test = "hexo" 
    end 
    def test=(value)
        @test=value
    end 
    def test 
        @test 
    end
end
p1 = Person.new("ku")
p1.test=("omg") # 括号可以省略#p1.test="omg"
p1.test
attr_accessor
class Person 
    attr_accessor :test
end

方法封装

默认是public公开,可设置private 私有访问、 protected受保护的访问
class Person 
    def public_method 
    end
    private
    def private_method 
    end
    protected
    def protected_method 
    end
end

类的继承

class Pet 
    attr_accessor :name, :age
end

class Cat < Pet

end
class Dog < Pet

end