发布于 2016-01-25 04:53:56 | 92 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Ruby教程,程序狗速度看过来!

Ruby编程语言

Ruby,一种为简单快捷的面向对象编程(面向对象程序设计)而创的脚本语言,在20世纪90年代由日本人松本行弘开发,遵守GPL协议和Ruby License。它的灵感与特性来自于 Perl、Smalltalk、Eiffel、Ada以及 Lisp 语言。


这篇文章主要介绍了Ruby面向对象编程详解,本文讲解了类的定义、定义对象、initialize方法、实例变量、类变量、类常量、类的继承等内容,需要的朋友可以参考下

Ruby是纯面向对象的语言,所有项目似乎要Ruby中为一个对象。Ruby中的每个值是一个对象,即使是最原始的东西:字符串,数字甚至true和false。即使是一个类本身是一个对象,它是Class类的一个实例。本章将通过所有功能涉及到Ruby的面向对象。

类是用来指定对象的形式,它结合了数据表示和方法操纵这些数据,转换成一个整齐的包。在一个类的数据和方法,被称为类的成员。

Ruby类的定义:

定义一个类,定义的数据类型的草图。 这实际上并不定义任何数据,但它定义的类名字的意思什么,即是什么类的对象将包括这样一个对象上执行什么操作可以。

类定义开始与关键字class类名和 end 分隔。例如,我们定义Box类使用class关键字如下:


class Box
   code
end

名称必须以大写字母开始,按照约定名称中包含多个单词,每个单词没有分隔符(驼峰式)一起执行。

定义Ruby的对象:

类为对象的蓝图,所以基本上是一个从一个类对象被创建。我们声明一个类的对象使用new关键字。下面的语句声明了两个对象,Box 类:


box1 = Box.new
box2 = Box.new

initialize方法:

initialize方法是一个标准的Ruby类的方法,和其它面向对象编程语言的构造方法有相同的方式工作。 initialize方法是有用的,在创建对象的时候,一些类变量初始化。这种方法可能需要的参数列表,它像其他Ruby之前的方法用def关键字定义,如下所示:


class Box
   def initialize(w,h)
      @width, @height = w, h
   end
end

实例变量:

实例变量是类的一种属性,一旦我们使用的类对象被创建的对象的属性。每个对象的属性被分别赋值的并与其它对象共享,它们在类的内部使用@操作符访问,但访问类之外的,我们使用的公共方法被称为访问器方法。如果我们把上述定义的类 Box,然后 @width 和 @height 类 Box实例变量。


class Box
   def initialize(w,h)
      # assign instance avriables
      @width, @height = w, h
   end
end

访问器和setter方法​​:

为了外部能访问类的变量,它们必须定义存取器方法,这些存取器方法也被称为getter方法。下面的例子演示了如何使用访问器方法:


#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # accessor methods
   def printWidth
      @width
   end

   def printHeight
      @height
   end
end

# create an object
box = Box.new(10, 20)

# use accessor methods
x = box.printWidth()
y = box.printHeight()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"


当上面的代码执行时,它会产生以下结果:

Width of the box is : 10
Height of the box is : 20

类似的存取方法用于访问的变量值,Ruby提供了一种方法来从类的外部设置这些变量的值,那就是setter方法​​,定义如下:

#!/usr/bin/ruby -w

# define a class class Box    # constructor method    def initialize(w,h)       @width, @height = w, h    end

   # accessor methods    def getWidth       @width    end    def getHeight       @height    end

   # setter methods    def setWidth=(value)       @width = value    end    def setHeight=(value)       @height = value    end end

# create an object box = Box.new(10, 20)

# use setter methods box.setWidth = 30 box.setHeight = 50

# use accessor methods x = box.getWidth() y = box.getHeight()

puts "Width of the box is : #{x}" puts "Height of the box is : #{y}"


当上面的代码执行时,它会产生以下结果:

Width of the box is : 30
Height of the box is : 50

实例方法:

也以同样的方式,因为我们使用def关键字定义其他方法,并按下图所示仅对使用一个类的实例,它们可以被用来定义该实例方法。它们的功能不局限于访问实例变量,他们也可以按要求做更多的事情。


#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
      @width * @height
   end
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"


当上面的代码执行时,它会产生以下结果:

Area of the box is : 200

类的方法和变量:

类变量是一个变量,这是一个类的所有实例之间共享。该变量是一个实例,它是可访问对象实例。两个@字符类变量带有前缀(@@)。在类定义类变量必须初始化,如下所示。

类方法的定义使用:def self.methodname() 以 end 字符结束,将被称为使用classname.methodname类名,在下面的例子所示:


#!/usr/bin/ruby -w

class Box
   # Initialize our class variables
   @@count = 0
   def initialize(w,h)
      # assign instance avriables
      @width, @height = w, h

      @@count += 1
   end

   def self.printCount()
      puts "Box count is : #@@count"
   end
end

# create two object
box1 = Box.new(10, 20)
box2 = Box.new(30, 100)

# call class method to print box count
Box.printCount()


当上面的代码执行时,它会产生以下结果:

Box count is : 2

to_s 方法:

所定义的任何类的实例应该有一个 to_s 方法返回一个字符串形式表示对象。下面以一个简单的例子来表示一个Box对象,在宽度和高度方面:


#!/usr/bin/ruby -w

class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # define to_s method
   def to_s
      "(w:#@width,h:#@height)"  # string formatting of the object.
   end
end

# create an object
box = Box.new(10, 20)

# to_s method will be called in reference of string automatically.
puts "String representation of box is : #{box}"


当上面的代码执行时,它会产生以下结果:

String representation of box is : (w:10,h:20)

访问控制:

Ruby提供了三个级别的保护实例方法的级别:public, private 和 protected。 Ruby没有应用实例和类变量的任何访问控制权。

Public Methods: 任何人都可以被称为public方法。方法默认为公用初始化,这始终是 private 除外。 .

Private Methods: private方法不能被访问,或者甚至从类的外部浏览。只有类方法可以访问私有成员。

Protected Methods: 受保护的方法可以被调用,只能通过定义类及其子类的对象。访问保存在类内部。

以下是一个简单的例子来说明三个访问修饰符的语法:


#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # instance method by default it is public
   def getArea
      getWidth() * getHeight
   end

   # define private accessor methods
   def getWidth
      @width
   end
   def getHeight
      @height
   end
   # make them private
   private :getWidth, :getHeight

   # instance method to print area
   def printArea
      @area = getWidth() * getHeight
      puts "Big box area is : #@area"
   end
   # make it protected
   protected :printArea
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"

# try to call protected or methods
box.printArea()


当上面的代码被执行时,产生下面的结果。在这里,第一种方法被调用成功,但第二种方法给一个提示。

Area of the box is : 200
test.rb:42: protected method `printArea' called for #
<Box:0xb7f11280 @height=20, @width=10> (NoMethodError)

类的继承:

在面向对象的编程中最重要的概念之一是继承。继承允许我们定义一个类在另一个类的项目,这使得它更容易创建和维护应用程序。

继承也提供了一个机会,重用代码的功能和快速的实现时间,但不幸的是Ruby不支持多级的继承,但Ruby支持混入。一个mixin继承多重继承,只有接口部分像一个专门的实现。

当创建一个类,而不是写入新的数据成员和成员函数,程序员可以指定新的类继承现有类的成员。这种现有的类称为基类或父类和新类称为派生类或子类。

Ruby也支持继承。继承和下面的例子解释了这个概念。扩展类的语法很简单。只需添加一个<字符的超类声明的名称。例如,定义Box类的子类classBigBox:


#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
      @width * @height
   end
end

# define a subclass
class BigBox < Box

   # add a new instance method
   def printArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end

# create an object
box = BigBox.new(10, 20)

# print the area
box.printArea()

当上面的代码执行时,它会产生以下结果:


Big box area is : 200

方法重载:

虽然可以在派生类中添加新的函数,但有时想改变的行为已经在父类中定义的方法。只需通过保持相同的方法名和重写该方法的功能,如下图所示,在这个例子可以这样做:


#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
      @width * @height
   end
end

# define a subclass
class BigBox < Box

   # change existing getArea method as follows
   def getArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end

# create an object
box = BigBox.new(10, 20)

# print the area using overriden method.
box.getArea()

运算符重载:

我们想“+”运算符使用+,*操作由一个标量乘以一箱的宽度和高度,这里是一个版Box类的定义及数学运算符:


class Box
  def initialize(w,h) # Initialize the width and height
    @width,@height = w, h
  end

  def +(other)         # Define + to do vector addition
    Box.new(@width + other.width, @height + other.height)
  end

  def -@               # Define unary minus to negate width and height
    Box.new(-@width, -@height)
  end

  def *(scalar)        # To perform scalar multiplication
    Box.new(@width*scalar, @height*scalar)
  end
end

冻结对象:

有时候,我们要防止被改变的对象。冻结对象的方法可以让我们做到这一点,有效地把一个对象到一个恒定。任何对象都可以被冻结通过调用Object.freeze。不得修改冻结对象:不能改变它的实例变量。

可以使用Object.frozen?语句检查一个给定的对象是否已经被冻结,被冻结的情况下的对象语句方法返回true,否则返回false值。下面的示例 freeze 的概念:


#!/usr/bin/ruby -w

# define a class
class Box
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # accessor methods
   def getWidth
      @width
   end
   def getHeight
      @height
   end

   # setter methods
   def setWidth=(value)
      @width = value
   end
   def setHeight=(value)
      @height = value
   end
end

# create an object
box = Box.new(10, 20)

# let us freez this object
box.freeze
if( box.frozen? )
   puts "Box object is frozen object"
else
   puts "Box object is normal object"
end

# now try using setter methods
box.setWidth = 30
box.setHeight = 50

# use accessor methods
x = box.getWidth()
y = box.getHeight()

puts "Width of the box is : #{x}"
puts "Height of the box is : #{y}"

当上面的代码执行时,它会产生以下结果:


Box object is frozen object
test.rb:20:in `setWidth=': can't modify frozen object (TypeError)
        from test.rb:39

类常量:

可以在类里定义分配一个直接的数字或字符串值,而不使用其定义一个变量为@@ 或 @。按照规范,我们保持常量名大写。

一个常量一旦被定义就不能改变它的值,但可以在类里像常量一样直接访问,但如果要访问一个类之外的常量,那么要使用类名::常量,所示在下面的例子。


#!/usr/bin/ruby -w

# define a class
class Box
   BOX_COMPANY = "TATA Inc"
   BOXWEIGHT = 10
   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end
   # instance method
   def getArea
      @width * @height
   end
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
puts Box::BOX_COMPANY
puts "Box weight is: #{Box::BOXWEIGHT}"

当上面的代码执行时,它会产生以下结果:


Area of the box is : 200
TATA Inc
Box weight is: 10

类常量继承和实例方法一样,可以覆盖。

创建对象使用分配:

当创建一个对象,而不调用它的构造函数初始化,即可能有一个情况:采用 new 方法,在这种情况下可以调用分配,这将创造一个未初始化的对象,看下面的例子:


#!/usr/bin/ruby -w

# define a class
class Box
   attr_accessor :width, :height

   # constructor method
   def initialize(w,h)
      @width, @height = w, h
   end

   # instance method
   def getArea
      @width * @height
   end
end

# create an object using new
box1 = Box.new(10, 20)

# create another object using allocate
box2 = Box.allocate

# call instance method using box1
a = box1.getArea()
puts "Area of the box is : #{a}"

# call instance method using box2
a = box2.getArea()
puts "Area of the box is : #{a}"

当上面的代码执行时,它会产生以下结果:


Area of the box is : 200
test.rb:14: warning: instance variable @width not initialized
test.rb:14: warning: instance variable @height not initialized
test.rb:14:in `getArea': undefined method `*' 
   for nil:NilClass (NoMethodError) from test.rb:29

类信息:

如果类定义的可执行代码,这意味着他们在执行的上下文中一些对象:自身都必须引用的东西。让我们来看看它是什么。


#!/usr/bin/ruby -w

class Box
   # print class information
   puts "Type of self = #{self.type}"
   puts "Name of self = #{self.name}"
end

当上面的代码执行时,它会产生以下结果:


Type of self = Class
Name of self = Box

这意味着,一个类的定义,作为当前对象的类并执行。在元类和其超类的方法将在执行过程中使用的方法定义。



最新网友评论  共有(0)条评论 发布评论 返回顶部
推荐阅读
最新资讯

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务