Rails中require、load、include、extend的区别
2014-05-29 16:28
441 查看
以下是对:require、load、include、extend的区别:
1)、require方法是加载一个文件,只加载一次,如果多次加载会返回false,一般在使用require加载一个文件的时候不需要加扩展名。如要加载test.rb文件时,require ‘test’。
2)、load方法跟require方法类似,也是加载一个文件,但是也有不同,就是它可以多次加载,而且必须制定扩展名。如要加载文件test.rb文件时, load "test.rb"
3)、include方法是引入模块,前提是你在映入了库之后,你可以在你的库文件中定义module,然后通过include引入,但是这里必须注意,使用include引入的module中的方法和变量为实例方法和实例变量,而不是类方法和类变量。更进一步说,即使你的类还在运行,这个时候你去改变了你引入的module的定义,你就会相应的改变引入该模块的类的行为。
test.rb :
module Include_test
def say
"This class is of type: #{self.class}"
end
end
class Test
require 'test'
include 'Include_test'
end
Test.say #会报未定义该方法
Test.new.say #This class is of type: Test
4)、extend方法类似于include方法,但是通过extend映入的方法和变量会成为类方法和变量,对象实例是没有办法去调用的
test.rb :
module Include_test
def say
"This class is of type: #{self.class}"
end
end
class Test
require 'test'
extend 'Include_test'
end
Test.say #This class is of type: Test
Test.new.say #会报未定义该方法
1)、require方法是加载一个文件,只加载一次,如果多次加载会返回false,一般在使用require加载一个文件的时候不需要加扩展名。如要加载test.rb文件时,require ‘test’。
2)、load方法跟require方法类似,也是加载一个文件,但是也有不同,就是它可以多次加载,而且必须制定扩展名。如要加载文件test.rb文件时, load "test.rb"
3)、include方法是引入模块,前提是你在映入了库之后,你可以在你的库文件中定义module,然后通过include引入,但是这里必须注意,使用include引入的module中的方法和变量为实例方法和实例变量,而不是类方法和类变量。更进一步说,即使你的类还在运行,这个时候你去改变了你引入的module的定义,你就会相应的改变引入该模块的类的行为。
test.rb :
module Include_test
def say
"This class is of type: #{self.class}"
end
end
class Test
require 'test'
include 'Include_test'
end
Test.say #会报未定义该方法
Test.new.say #This class is of type: Test
4)、extend方法类似于include方法,但是通过extend映入的方法和变量会成为类方法和变量,对象实例是没有办法去调用的
test.rb :
module Include_test
def say
"This class is of type: #{self.class}"
end
end
class Test
require 'test'
extend 'Include_test'
end
Test.say #This class is of type: Test
Test.new.say #会报未定义该方法
相关文章推荐
- Ruby 中 require load extend include 区别
- Ruby中Require、Load、Include和Extend的区别
- Ruby中require、load、include、extend的区别介绍
- Ruby中Require、Load、Include和Extend的区别
- require,include,load,extend的用途和区别
- require,include,load,extend的用途和区别
- require,include,load,extend的用途和区别
- ruby中load,require以及include,extend的区别
- differences between Require, Load, Include and Extend methods
- Ruby中require,load,和include的区别
- Ruby 里的 include,require,load的显著区别
- 区别Ruby的require,load,和include
- 区别Ruby的require,load,和include
- [转]Ruby中require、load和include区别
- Ruby中Require、Load、Include和Extend的区别
- 区别Ruby的require,load,和include
- 区别Ruby的require,load,和include
- 区别Ruby的require,load,和include
- Ruby中require,load,include和extend方法的区别
- Ruby中require,load,include,extend的区别