易截截图软件、单文件、免安装、纯绿色、仅160KB

Ruby学习笔记三——类


#一、定义一个类
class Person
  def initialize(name,age=18)
    @name=name;
    @age=age;
    @motherland="china";
  end
  def talk
    puts "my name is "+@name+" and I am "+@age.to_s
    if @motherland == "china"
      puts "I am a Chinese."
    else
      puts "I am a foreigner."
    end
  end#talk结束
  attr_writer:motherland 
  attr_writer:age
end#class结束
p1=Person.new("Zhangren",10);
p1.talk;
p1.motherland="abc";
p1.talk;
p1.age=20;
p1.talk;
#二、继承自一个类
class Student < Person
  def talk
    #super;#这会调用父类talk中的代码
    puts "I am a student. my name is "+@name+", age is "+@age.to_s
  end # talk方法结束
end # Student类结束
p3=Student.new("kaichuan",25); p3.talk
p4=Student.new("Ben"); p4.talk
#Ruby没有重载方法,因为参数没有类型,所以没法重载。有多态,不过不太明显,因为变量都没有类型,所以谈不上父类引用指向子类对象,都是统一的引用。
#三、变量动态性
# E5.3-1.rb
a=5
b="hh"
puts "a = #{a} #{b} #{a}"
puts "b = #{b}"
#四、重写
def talk (a,b=1)
puts "This is talk version 2."
end
def talk (a)
puts "This is talk version 1."
end
talk (2) # This is talk version 1.
#talk (2,7) # 报错,因为重写之后,只有后一个有用,没有重载。父子类中也是重写。
#五、Ruby的变量等标识名称区分太小写。全局变量用$引用,实例变量用@(也就是成员变量,因为不需要声明,都是直接用),类变量用@@(其实就相当于静态变量)
$a="\n a is a global value"
puts $a
class StudentClass
  @@count=0
  def initialize( name )
    @name = name
    @@count+=1
  end
  def talk
    puts "I am #@name, This class have #@@count students."
  end
end
p1=StudentClass.new("Student 1 ")
p2=StudentClass.new


相关文档:

Ruby的装饰器模式实现

class Tree
def initialize
puts "Make a normal tree"
end
def decorate
puts "Make sure the tree won\'t fall"
end
end
class RedBalls < Tree
def initialize(tree)
@parent = tree;
end
def decorate
@parent.decorate
puts "Put on some red balls"
end
end ......

自动化测试之路(三) ruby里的get与set方法

照例可以先看端程序
class Person
 
  def initialize( name,age=18 )
    @name = name
    @age = age
    @motherland = "China"
  end
 
  def talk
    puts "my name is "+@name+", age is "+@age.to_s
 &n ......

升级到snow leopard后ruby的问题

1. ruby已成为1.87 2. 必须先安装安装光盘里的新的xcode,在"optional"目录里 3. 可能需要重新安装macport http://trac.macports.org/wiki/Migration 4. 或者升级macport http://weblog.rubyonrails.org/2009/8/30/upgrading-to-snow-leopard $ sudo port selfupdate
$ sudo port sync
$ sudo port upgrade --force insta ......

Ruby学习笔记二——数组

#一、数组引用
arr=[3,4,5,6,7,8,9]
puts arr[0] #3
puts arr.first #3
puts arr[arr.length-1] #9
puts arr[arr.size-1] #9
puts arr.last #9
puts arr[-1] #9
puts arr[-2] #8
print arr[1..3] ,"\n" #456
print arr[-3,4] ,"\n" #789,从-3开始 ,打印4个元素,这里只有三个
#Ruby的数组大小是动态的,你能够 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号