Ruby 中的“include”和“extend”的区别


使用 Ruby 的 **include** 关键字时,我们导入的只是一个模块代码,但是我们不能直接通过该类访问导入模块中的方法,因为它基本上是一个父类的子类

另一方面,当我们在 Ruby 中使用 **extend** 关键字时,我们导入的还是一个模块代码,但是方法是以类方法导入的。如果我们尝试使用该类的实例访问我们导入的方法,编译器会抛出一个错误。

现在让我们在 Ruby 代码中使用这两个关键字来了解它们的差异。

示例 1

请看下面的代码。

# Creating a module that contains a method
module MyModule
   def first_method
      puts 'This is the First Method.'
   end
end

class First_Class
   include MyModule
end

class Second_Class
   extend MyModule
end

# object access
First_Class.new.first_method

# class access
Second_Class.first_method

输出

该代码会产生如下输出。

This is the First Method.
This is the First Method.

示例 2

现在让我们考虑一个用例,我们希望导入类上的实例方法以及类方法。在这种情况下,我们将同时使用 include 和 **extend** 关键字。

请看下面的代码

# Creating a module that contains a method
module MyModule
   def logs(x)
      puts x
   end

end
class First_Class
   include MyModule
   extend MyModule
end

First_Class.new.logs("It's a chilly overcast day.")
First_Class.logs("Keep an umbrella with you.")

输出

该代码会产生如下输出。

It's a chilly overcast day.
Keep an umbrella with you.

更新日期:2022 年 4 月 12 日

1 千次以上浏览

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.