Ruby如何定义一个类

2023-07-06   


类是对具有同样属性和同样行为的对象的抽象,Ruby中类的声明使用class关键字。定义类的语法如下,
   class ClassName
   def method_name(variables)
   #some code
   end
   end
   类的定义要在class…end之间,在上面的格式中,ClassName是类名,类名必须以大写字母开始,也就是说类名要是个常量。
  
   看下面的例子:
   class Person
   def initialize(name, gender, age)
   @name = name
   @gender = gender
   @age = age
   end
   end
  
   若某个类已经被定义过,此时又用相同的类名进行类定义的话,就意味着对原有的类的定义进行追加。
  
   class Test
   def meth1
   puts “This is meth1″
   end
   end
  
   class Test
   def meth2
   puts “This is meth2″
   end
   end
  
   在Test类中,原有meth1方法,我们又追加了meth2方法,这时候,对于Test类的对象,meth1和meth2同样可用。


相关内容:

  1. 解释一下ruby中的特殊方法与特殊类
  2. Ruby如何实现动态方法调用
  3. ruby如何进行集成操作?Ruby能进行多重继承吗?
  4. 介绍一下Ruby中的对象,属性和方法
  5. 既然说Ruby中一切都是对象,那么Ruby中类也是对象吗
  6. 既然说Ruby中一切都是对象,那么Ruby中类也是对象吗