ruby learning-- Difference between require and include

原创 2013年07月16日 21:31:27


整理自: http://stackoverflow.com/questions/318144/what-is-the-difference-between-include-and-require-in-ruby


首先要知道这两者差别很大。
  • 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.new
require MyModule     # Error
上面两行代码会报错,can not convert Module to String( TypeError )
如果将require改为include,编译通过。

ruby小白一枚,如有错误,敬请指正~

differences between Require, Load, Include and Extend methods

Here are the differences between Require, Load, Include and Extend methods:IncludeWhen you Include a...

Difference_between_PLMN_and_PSTN

  • 2008年11月06日 10:48
  • 41KB
  • 下载

python中下划线,双下划线,首尾双下划线的区别(Difference between _, __ and __xx__ in Python)

Difference between _, __ and __xx__ in Python When learning Python many people don't really under...
  • Sinchb
  • Sinchb
  • 2013年03月13日 13:24
  • 2871

Difference between FX2 and FX2LP

  • 2013年11月06日 14:02
  • 512KB
  • 下载

What is the basic difference between NSTimer, NSTask, NSThread and NSRunloop?

Each program runs in at least one thread. You can think of each thread as a separate process of prog...
  • Koupoo
  • Koupoo
  • 2011年08月15日 11:50
  • 430

What is the basic difference between NSTimer, NSTask, NSThread and NSRunloop ?

(转)http://www.devdiv.com/forum.php?mod=viewthread&tid=38980&extra=page%3D1%26filter%3Dtypeid%26typei...

Difference Between Performance Testing, Load Testing and Stress Testing – With Examples

1) Performance Testing: Performance testing is the testing, which is performed, to ascertain how th...

What is the Difference Between http and https?

Hypertext Transfer Protocol (http) is a system for transmitting and receiving information across the...

In SQL, what is the difference between a left join and a left outer join?

There is actually no difference between a left join and a left outer join – they both refer to the e...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:ruby learning-- Difference between require and include
举报原因:
原因补充:

(最多只允许输入30个字)