ruby对象学习示例

class Person
  attr_writer:info  ##可写的成员变量
  @@count = 0  ##静态变量
  def initialize(name,age,gender)  ##构造方法
    @name=name
    @age=age
    @gender=gender
    @info="#{name} #{age} #{gender}"
    @@count+=1
  end
  def info_ref
    @info
  end
  def info
    puts @info
  end
  def Person.getCount   ##静态方法
    @@count
  end
end

class Derive < Person    ##继承
  def info           ##重载
    puts "derive"
    super
  end
end

people = Derive.new('jone',22,'female')
puts people.info

people1 = Derive.new('jone',22,'female')
class << people1   ##特殊类和特殊方法
  def info
    puts "this is people1 method"
  end
end
puts people1.info
puts Person.getCount

puts Person.object_id  ##元对象,类对象和实例对象都是对象,都有一个object_id,我们可以像调用一个实例对象的方法去调用类对象的方法
puts people.object_id
Object.class
Object.superclass


class ReTest ##ruby的动态性,可以重新定义一个对象的方法,可以用undef_method去掉一个方法的定义
  def meth
    puts "this is a method"
  end
end
retest = ReTest.new
retest.meth
class ReTest
  def meth
    puts "this is a another method"
  end
end
retest = ReTest.new
retest.meth
class ReTest
  undef_method(:meth)
end
obj = ReTest.new
obj.meth  

 

输出:

D:\software\Ruby192\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) D:/project/rubyDemo/test1.rb
D:/project/rubyDemo/test1.rb:65:in `<top (required)>': undefined method `meth' for #<ReTest:0xc95160> (NoMethodError)
derive
    from -e:1:in `load'
jone 22 female
    from -e:1:in `<main>'

this is people1 method

2
6597492
6597360
this is a method
this is a another method

Process finished with exit code 1

 

你可能感兴趣的:(Ruby)