Rails中require、load、include、extend的区别

以下是对: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 #会报未定义该方法

发布了25 篇原创文章 · 获赞 0 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章