博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

sislcb

寻找自己
sislcb.cublog.cn
Ruby On Rails入门经典 第三章 类和对象
创建类:
class Animal
end
 
class Animal
  def initialize
    @color = "red"
  end
 
  def get_color
    return @color
  end
end
@color是实例变量,实例变量用于在对象中保存对象
 
创建对象:
animal = Animal.new
puts "The new animal is " + animal.get_color
new调用了 initialize方法创建对象
 
把上面的initialize改为:
def initialize(color)
  @color = color
end
则调用变为: animal = Animal.new("brown")
 
ruby的属性:
可读属性:
attr_reader:color
可写属性:
atter_writer:color
可读写属性:
attr_accessor
 
继承类:
class Dog < Animal
  def initialize(color, sound)
    super(color)
    ..
  end
end
Dog继承了父类的构造函数,使用super函数调用
同时,get_color方法也继承了,因为ruby默认就是public的,而不是private的。
 
重写方法,相当于覆盖:
class Dog < Animal
  ...
  def get_color
    return "blue"
  end
end
则会覆盖了父类Animal的get_color方法
 
类变量:
@@前缀创建类变量,类的所有实例共享一个类变量
class Animal
  @@number_animals = 0;
  def initialize(color)
    @color = color
    @@number_animals += 1
  end
 
  def get_number_animals
    return @@number_animals
  end
end
 
类方法:
只需要类名就可以调用的方法,只能使用类变量
class Mathematics
  def Mathematics.add(operand_one, operand_two)
    return operand_one + operand_two
  end
end
 
创建模块:
使用module关键字
 
module Sentence
  def Sentence.add(word_one, word_two)
    return word_one + " " + word_two
  end
end
使用模块:
require 'sentence'
puts "2 + 3 = " + Sentence.add(2, 3).to_s
不能使用模块创建实例
require 'sentence' 相当于 include 'sentence.rb'
模块中还可以包含类:
module Mathematics
  class Adder
    def Adder.add(operand_one, operand_two)
      return operand_one + operand_two
    end
  end
end
 
混和插入:
可以把模块中的方法包含到类中
 
module Adder
  def add(operand_one, operand_two)
    return operand_one + operand_two
  end
end
 
module Subtracter
  def subtract(operand_one, operand_two)
    return operand_one - operand_two
  end
end
 
class Calculator
  include Adder
  include Subtracter
end
 
calculator = Caculator.new()

发表于: 2007-11-06,修改于: 2007-11-06 23:11,已浏览478次,有评论0条 推荐 投诉

给我留言
版权所有 ChinaUnix.net 页面生成时间:4.24386