ruby learning-- Difference between require and include
来源:互联网 发布:办公制图软件 编辑:程序博客网 时间:2024/04/29 13:03
首先要知道这两者差别很大。
- require做的工作就像其他绝大多数语言的include做的工作一样: 运行另一个文件。它也会追踪你过去require过的文件且不会require同一个文件两次。它和load()方法很像,但意图不一样,load()是用来执行代码的,而require是用来导入库的。
- include将另一个模块的所有函数都取为己用并将它们包含进当前模块。include处理的是语言层次的事情而require处理的是文件层次的事情。 include是用其他模块扩展类的主要方法,通常也成为mix-ins(混入)。类可以混合一个模块,得到这个模块提供的所有方法。比如所有提供 each 方法的类可以混合 Enumerable 模块,来得到这个模块提供的所有方法,当然这些方法都会调用 each 做循环。
所以当你只是想用一个模块,而不是扩展它或是混合它,你可能会使用require。
简而言之,ruby 的require就像c语言的include,而ruby的include几乎完全不像c语言的include。
如果你用一个模块来扩展(extend)一个类的话,意味着你将该模块的方法引入为类方法,
如果你将一个模块包含进(include)一个类,意味着你将该模块的方法引入为实例方法。
例子如下:
module A def say puts "this is module A" end end class B include A end class C extend A end
B.say
=> undefined method 'say' for B:Class
B.new.say
=> this is module A
C.say
=> this is module A
C.new.say
=> undefined method 'say' for C:Class
ps:
所谓的类方法和实例方法的区别在于,类方法也叫静态方法,指用static修饰的方法,属于类本身的方法,不属于类的某一个实例对象。类方法中不可直接使用实例变量,调用方式有3种:直接调用,类名.方法名,对象名.方法名。 实例方法指不用static关键字修饰的方法,每个实例对象都有自己的实例方法,互相独立,不共享,调用方式只能是对象名.方法名。
还有一个细节就是模块不能直接被require
MyModule = Module.newrequire MyModule # Error
上面两行代码会报错,can not convert Module to String( TypeError )
如果将require改为include,编译通过。
ruby小白一枚,如有错误,敬请指正~
- ruby learning-- Difference between require and include
- the difference between require() and include() in php
- Difference between forward and include of RequestDispatcher
- The difference between J2ee and Ruby
- The Difference Between Ruby Symbols and Strings
- Difference between JSP include directive and JSP include action
- differences between Require, Load, Include and Extend methods
- the difference between data mining and meachine learning
- require load include ruby
- The difference between (()) and ().
- difference between "<" and "<<"
- What is the difference between a parametric learning algorithm and a nonparametric learning method?
- What’s the Difference Between Artificial Intelligence, Machine Learning, and Deep Learning?
- ruby require include的区别
- php--include and require
- What is the difference between #import and #include in Objective-C?
- Difference Between typedef and #define
- Difference between PCDATA and CDATA
- 2013年7月编程语言排行榜
- wcf系列5天速成——第一天 binding的使用(1)
- 获得document的iframe时有两种方法
- OTA本质与实现流程分析
- oracle的启动和关闭
- ruby learning-- Difference between require and include
- Google Wallet
- Java Tcp Socket聊天系统模型
- iOS: NSKeyedArchiver的方法encodeObject:forKey:
- RedHat安装WebLogic11g软件及Web工程的部署
- nmap
- 在ubuntu下配置ibus五笔输入法
- 编辑距离小练
- JNDI配置数据源