ruby学习笔记-类和对象

1.ruby定义类ruby

class Custom

end

在ruby中,类老是以关键字class开始,后跟类的名称。类名的首字母应该大写。函数

能够使用关键字end终止一个类,也能够不用。类中的全部数据成员都是介于类定义和end关键字之间。code

2.ruby类中的变量,ruby提供了四种类型的变量对象

局部变量:局部变量是在方法中定义的变量。局部变量在方法外是不可用的。局部变量以小写字母或_开始it

实例变量:实例变量能够跨任何特定的实例或对象中的方法使用。实例变量在变量名以前放置符号@class

类变量:类变量能够跨不一样的对象使用。类变量在变量名以前放置符号@@变量

全局变量:类变量不能跨类使用。全局变量老是以符号$开始。方法

class Customer
    @@no_of_customers=0
end

3.在ruby中使用new方法建立对象数据

new是一种独特的方法,在ruby库中预约义,new方法属于类方法。di

cust1 = Customer.new
cust2 = Customer.new

4.自定义方法建立ruby对象

能够给方法new传递参数,这些参数可用于初始化类变量。使用自定义的new方法时,须要在建立类的同时声明方法initialize,initialize是一种特殊类型的方法,将在调用带参数的类new方法时执行。

class Customer
  @@no_of_customers=0
  def initialize(id,name,addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
  end
end

5.ruby中的成员函数

class Sample
   def hello
       puts "----hello ruby------"
   end
end

6.类案例

class Customer
    @@no_of_customers=0
    def initialize(id,name,addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
    end
    
    def display_details
        puts "customer id #@cust_id"
        puts "customer name #@cust_name"
        puts "customer address #@cust_addr"
    end
    
    def total_no_of_customers
        @@no_of_customers += 1
        puts "total number of customers:#@@no_of_customers"
    end
    
end

#自定义类的new方法后,原new方法不能使用
#cust1 = Customer.new
#cust2 = Customer.new

cust3 = Customer.new("3","John","Hubei")
cust4 = Customer.new("4","Paul","Hunan")

puts cust3
cust4.display_details
cust4.total_no_of_customers
相关文章
相关标签/搜索