Ruby是动态语言,允许随时更改类定义,如我们在定义一个类时,该类已经存在,则此时的定义是对先前类的追加,而不是重新定义.

 

class Apple
  def show
    puts 
"一个苹果"
  end
end
a
=Apple.new()
a.show

class Apple
  #为Apple类追加一个test方法
  def test
    puts 
"口感不错"
  end
end

a
=Apple.new()
a.show
a.test

 

使用特殊类定义为某个对像追加方法和变量.

 

class << a
  def name
    puts 
"富士"
  end
end

a.show
a.name

 

 

使用特殊类定义为a对象追加了个name方法后,a就可以调用name方法,但其它的Apple实例依然没有name方法.

相关文章:

  • 2022-03-09
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-25
  • 2022-12-23
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2021-12-14
相关资源
相似解决方案