设为首页收藏本站

嘻皮客娱乐学习网

 找回密码
 中文注册
搜索
打印 上一主题 下一主题
开启左侧

[面试题库] Ruby如何定义一个类

[复制链接]
跳转到指定楼层
楼主
发表于 2014-11-30 20:36:00 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
类是对具有同样属性和同样行为的对象的抽象,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同样可用。
回复

使用道具 举报

小黑屋|手机版|嘻皮客网 ( 京ICP备10218169号|京公网安备11010802013797  

GMT+8, 2024-5-15 02:39 , Processed in 0.208764 second(s), 26 queries , Gzip On.

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表