在 Ruby 中包含 v/s 扩展
include用于导入模块代码。当我们尝试使用类直接访问导入模块的方法时,Ruby 会抛出错误,因为它是作为超类的子类导入的。因此,唯一的方法是通过类的实例来访问它。
扩展也用于导入模块代码,但扩展将它们作为类方法导入。当我们尝试使用类的实例访问导入模块的方法时,Ruby 会抛出错误,因为模块像扩展模块的实例一样被导入到超类。因此,唯一的方法是通过类定义访问它。
简单来说,include 和extend 之间的区别在于“include”仅用于向类的实例添加方法,“extend”用于向类添加方法而不是向其实例添加方法。
例子 :
# Ruby program of Include and Extend
# Creating a module contains a method
module Geek
def geeks
puts 'GeeksforGeeks!'
end
end
class Lord
# only can access geek methods
# with the instance of the class.
include Geek
end
class Star
# only can access geek methods
# with the class definition.
extend Geek
end
# object access
Lord.new.geeks
# class access
Star.geeks
# NoMethodError: undefined method
# `geeks' for Lord:Class
Lord.geeks
输出
GeeksforGeeks!
GeeksforGeeks!
main.rb:20:in `': undefined method `geeks' for Lord:Class (NoMethodError)
如果我们想在一个类及其类方法上导入实例方法。我们可以同时“包含”和“扩展”它。
例子 :
# Ruby program to understand include and extend
# Creating a module contains a method
module Geek
def prints(x)
puts x
end
end
class GFG
# by using both include and extend
# we can access them by both instances
# and class name.
include Geek
extend Geek
end
# access the prints() in Geek
# module by include in Lord class
GFG.new.prints("Howdy") # object access
# access the prints() in Geek
# module by extend it in Lord class
GFG.prints("GeeksforGeeks!!") # class access
输出
Howdy
GeeksforGeeks!!