`

Ruby 的include和extend用法

    博客分类:
  • Ruby
阅读更多

Ruby使用include和extend来对class做补充。

假设有一个module:

module Person
  def about_me
     puts "This is about me."
  end
end

 

1, include <module name>

  1.1 使模块的方法变成类的实例方法:

class Student
  include Person
end
student = Student.new
student.about_me # puts "This is about me."
Student.about_me # 没有定义此方法,抛出异常。

   1.2 如何要让 Student 可以直接调用include module的方法,可以在 def self.included(c) ... end 实现,比如

 

module Person
  def about_me
     puts "This is about me."
  end
  def self.included(c)
   def c.call_me
     puts "This is class me"
   end
  end
end

   Student.call_me即可直接调用。

 

2, extend <module name>是直接变成类的类方法 ,相当于class << self. 

 

参考资料: http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby

分享到:
评论

相关推荐

    Ruby on Rails中的include和extend的常见用法

    本文将介绍浅谈Ruby on Rails中的include和extend。include主要用来将一个模块插入到一个类或者其它模块。extend用来在一个对象中引入一个模块,这个类从而也具备了这个模块的方法。

    interface:ruby 中的可实现接口

    Ruby 1.9+用法 只需使用您希望其实现对象定义的任何方法创建一个模块module RemoteControl # turns the device on def on end # turns the device off def off endend然后在您的类中使用implements方法(也别名为...

    sord:将YARD文档转换为Sorbet RBI和Ruby 3Steep RBS文件

    无论您打算使用Sorbet的RBI格式还是Ruby 3 / Steep的RBS格式,Sord都是在项目中快速采用类型的理想方法。 Sord具有以下功能: 自动为模块,类和方法生成签名 支持多种参数或返回类型( T.any / | ) 优雅地处理...

    ruby-comparateur:计算两个 HTML 文档的结构相似度

    这就是为什么您必须创建一个类并使用Comparateur include或extend它并根据需要使用它。 此实现还允许您构建自己的缓存系统。 安装 将此行添加到应用程序的 Gemfile 中: gem 'comparateur' 然后执行: $ bundle...

    Ruby中钩子方法的运用实例解析

    通过使用钩子方法,可以让我们在Ruby的类或模块的生命周期中进行干预,可以极大的提高编程的灵活性。 与生命周期相关的钩子方法有下面这些: 类与模块相关 Class#inherited Module#include Module#prepended ...

    class_profiler:简单的性能分析器,带有一些强大的元编程酒精

    类分析器 用于Ruby类的简单性能分析器。 只需将其包含在您的类的底部,然后让它分析您... include ClassProfiler #include it just before closing the class end 或者,如果您想要更可配置的内容,以仅测量特定的方法

    slugity:又一个猛烈的宝石

    描述 另一个 slugging gem,使用自定义映射选项将字符串转换为 slug。 安装 gem install slugity ... require 'slugity/extend_string' "one + two = three" . to_slug # =&gt; "one-plus-two-equals-three" 还

    eldritch:RubyDSL,它添加了并发编程结构以简化并行性

    用法 安装它gem install eldritch 要求它require 'eldritch' 使用它(请参阅下面的功能) 默认情况下,eldritch会将DSL注入全局范围。 如果您不希望这样做,则可以要求eldritch/safe而不是eldritch 。 require '...

    artist-song-modules-online-web-sp-000

    使用模块重构 目标 识别表明需要重构的“代码气味”。 使用模块重构多余的代码。 概述 在本实验中,我们有一个Artist类和一个Song类。...然后,我们将使用extend和include关键字将模块的功能借给Artist和Song

    artist-song-modules-v-000

    使用模块重构 目标 识别表明需要重构的“代码气味”。 使用模块重构多余的代码。 概述 在本实验中,我们有一个Artist类和一个Song类。... 然后,我们将使用extend和include关键字将模块的功能借给Ar

    refile-mongoid:允许MongoID与重新归档一起很好地播放

    Refile :: Mongoid 于扩展名。 安装 ...用法 require "refile/mongoid" class User include Mongoid :: Document extend Refile :: Mongoid :: Attachment attachment :profile_image end 执照

Global site tag (gtag.js) - Google Analytics