首页 > 其他 > 详细

2.ruby基本语法,类的定义

时间:2017-02-26 23:46:03      阅读:234      评论:0      收藏:0      [点我收藏+]

1.在ruby中的定义class,ruby中定义类也是以关键字class开头

  后面带着类名,类名以大写开头。一个类的结束以关键字end

  结束。如:

  class Customer

  end

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

  1>局部变量

    局部变量一般的被定义在方法中,方法外不可见。局部变量

    一般以小写字母或者_.开头。

  2>实例变量

    实例变量能被特殊的实例或者对象的可访问的方法访问。这就

    意味着实例变量被对象而改变。实例变量通常在变量名前加上

    (@)符号。

  3>类变量

    类变量可以被其他类访问。类变量属于类,在类的不同的实例中

    都可以访问,是类特有的。通常在变量名前加上(@@)符号。

  4>全局变量

    类变量不能在其他类中访问,如果你需要这样的变量,这样的变量

    可以跨类访问。全局变量通常在变量名前加上($)符号。

3.ruby创建对象,使用new方法

  class Customer

    @@no_of_customers = 1

  end

  

  cuts1 = Customer. new

  cuts2 = Customer. new

  默认的情况下,不用显示的定义初始化方法,在java中,就是构造方法,

  ruby也是有个默认的无参默认初始化方法。

  如下:

  class Customer

    @@no_of_customers = 1

    def initilize(id, name, addr)

      @cust_id = id

      @cust_name = name

             @cust_addr = addr

    end

  end

   可以使用带参数的初始化参数来创建对象的实例,如下:

  cust1 = Customer. new("1", "john", "shenzhen")

  cust2 = Customer. new("2", "tom", "shenzhen")

4.ruby类的方法成员

  class Sample

    def function

      statement 2

      statement 3

    end

  end

  如:

  class Sample

    def hello

      puts "hello ruby!"

    end

  end

  #使用对象,调用对象

  object = Sample.new

  object.hello

  #输出

  hello ruby!

5.我们来创建包含全局变量,实例变量,和方法

  class Customer

    @@no_of_customers = 0

    def initilize (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

  #Create Objects

  cust1 = Customer.new("1" , "john" , "hubei" )

  cust2 = Customer.new("2" , "tom" , "shenzhen")

  #Call Methods

  cust1.dispaly_details()

  cust1.total_no_of_customers()

  cust2.desplay_details()

  cust2.total_no_of_customers()

  

  

2.ruby基本语法,类的定义

原文:http://www.cnblogs.com/LvLoveYuForever/p/6457881.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!