ruby基础知识之 class&module
以下分别介绍了class方法和module方法,还有最简单的def方法。
其中module和class的区别下面会说,这里首先声明,def定义的方法,需要定义对象后才能调用,而class和module都能随意进入。
class方法
ruby里的方法分为:类方法和实例方法
类方法:通过类名直接调用的方法
可以写的形式一般是3类:
第一种:
class Fo
def self.bar
p "aa"
end
end
第二种:
class Foo
class << self
def bar
p "bb"
end
end
end
第三种:
class Fooo; end
def Fooo.bar
end
调用的时候:直接Foo.bar 这样调用即可。
实例方法:通过对象调用的方法
可以写成的形式也有3种:
第一种:
class Foo
def baz
p "mm"
end
end
第二种:
class Foo
attr accessor :baz
end
foo = Foo.new
foo.baz = "instance method"
第三种:这种方法只针对foo这一个对象有效,称为单例方法,函数范围很小
class Foo; end
foo = Foo.new
def foo.baz
p "instance method"
end
调用实例方法的时候,一定要先new一个对象出来
module(模块)方法
提前声明:module方法是ruby语言特有的,它是一个命名空间,避免定义了相同名称的函数或变量导致的冲突。
module也分为module实例方法和module类方法,它的写法其实与类方法是一毛一样的。比如:
上面这段代码就是一个模块类方法,特点是在定义方法和调用方法的时候都在前面加上了所在module的名字,这样定义的函数就叫module method 。
在定义方法名称的时候,我们不加module name,这样定义出来的方法就叫模块实例方法(module instance method),这种方法就是实例方法,只能被mixin到某个class中被引用。
module与class的区别:
1、module不能实例化,即module为实例方法的module时,它不能被自己引用,需要利用include方法引用到class中;
2、module不能继承,而class可以
常量定义:凡是首字母大写的,都是常量,包括class和module都是,常量在调用的时候用::
调用规则:
类调用用::或者.
实例调用只能用.
所以为了区分,一般类调用我们都用::
下面说一下class对module的调用:
module Mammal # 哺乳动物
def suckle # 哺乳
print "I can suckle my baby \n"
end
end module Flyable ·· #可飞行的
def fly #飞行
print "I can fly", "\n"
end
end class Chiropter #蝙蝠
include Mammal #蝙蝠是哺乳动物
include Flyable #蝙蝠可以飞行
end achiropter = Chiropter.new
achiropter.suckle
achiropter.fly
最新文章
- js小练习去掉指定的字符组成一句话输出
- Putty部署tomcat
- 漫谈可视化Prefuse(一)---从SQL Server数据库读取数据
- JavaWeb---总结(三)Tomcat服务器学习和使用(一)
- JS网页顶部进度条demo
- git使用记录(新手入门)
- 基于sqlite的Qt 数据库封装
- autofac 学习记录
- mysql 删除日志
- Struts1和Struts2的区别和对比(完整版)
- C语言头文件书写
- 为openwrt编译xd-h3c
- Mysql5.7在CentOs环境下定时备份数据库
- CentOS下安装yum
- LeetCode之“动态规划”:Unique Binary Search Trees &;&; Unique Binary Search Trees II
- 算法库中heap应用
- html5 的存储
- cSharp:use Activator.CreateInstance with an Interface?
- ActivityThread
- 雷林鹏分享:C# 类(Class)
热门文章
- python 生成器&;迭代器
- Python模块(进阶3)
- DVR_RDK编译报错
- 问题解决:java.sql.SQLException:Value &#39;0000-00-00&#39; can not be represented as java.sql.Date
- PHP使用in_array函数检查数组中是否存在某个值
- 使用ByPropertyName进行管道传输
- 虚拟机Centos安装docker小记
- CVPR 2016 paper reading (6)
- Google Map中的瓦片
- Faster Alternatives to glReadPixels and glTexImage2D in OpenGL ES