Ruby 中的包含和扩展有什么区别? [英] What is the difference between include and extend in Ruby?

查看:38
本文介绍了Ruby 中的包含和扩展有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始了解 Ruby 元编程.mixin/模块总是让我感到困惑.

Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me.

  • include:在目标类中混入指定的模块方法作为实例方法
  • extend:在目标类中混入指定的模块方法作为类方法
  • include: mixes in specified module methods as instance methods in the target class
  • extend: mixes in specified module methods as class methods in the target class

那么主要区别是这个还是潜伏着更大的龙?例如

module ReusableModule
  def module_method
    puts "Module Method: Hi there!"
  end
end

class ClassThatIncludes
  include ReusableModule
end
class ClassThatExtends
  extend ReusableModule
end

puts "Include"
ClassThatIncludes.new.module_method       # "Module Method: Hi there!"
puts "Extend"
ClassThatExtends.module_method            # "Module Method: Hi there!"

推荐答案

你说的对.然而,还有更多.

What you have said is correct. However, there is more to it than that.

如果你有一个类 Klazz 和模块 Mod,在 Klazz 中包含 Mod 给出了 Klazz 访问 Mod 的方法.或者你可以使用 Mod 扩展 Klazzclass Klazz 访问 Mod's 方法.但是您也可以使用 o.extend Mod 扩展任意对象.在这种情况下,单个对象获得 Mod 的方法,即使与 o 具有相同类的所有其他对象都没有.

If you have a class Klazz and module Mod, including Mod in Klazz gives instances of Klazz access to Mod's methods. Or you can extend Klazz with Mod giving the class Klazz access to Mod's methods. But you can also extend an arbitrary object with o.extend Mod. In this case the individual object gets Mod's methods even though all other objects with the same class as o do not.

这篇关于Ruby 中的包含和扩展有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆