zoukankan      html  css  js  c++  java
  • ruby中的extend 和 include

    include

    include是把module中定义的instance_method给mixin,然后当做类的实例方法使用(是因为module本身不能使用module的实例方法),给类进行实例化一个对象,然后对象再直接调用实例方法。

    1       module Mood
    2          def say
    3              p "hello, everyone!"
    4          end
    5       end
    6       class Person
    7           include Mood
    8       end
    9       Person.new.say

    #=>     "hello, everyone!"

    extend 是把module的方法导入到当前的模块当中,所以如果module是实例方法,在被mixin到类中时,就变成了module的类方法:

    eg:

    1      module Mood
    2          def say
    3              p "hello, everyone!"
    4          end
    5       end
    6       class Person
    7           extend Mood
    8       end
    9       Person.say

    #=>     "hello, everyone!"

    如果实例方法的module,被引用到类的实例方法中时,就仍混入为实例方法

    module Mood
         def say
              p "hello, everyone!"
          end
    end
    class Person
    end
    person = Person.new 
    person.extend(Mood)    
    person.say

    即,class类中用extend方法,若module为实例方法,则被转变为module的类方法;若放入class的实例方法,则module仍为实例;

    但是把module的类方法放入class的实例方法,则module不会改变,仍为类。

  • 相关阅读:
    recurse_array_change_key_case()递规返回字符串键名全为小写或大写的数组
    php循环创建目录
    ajaxFileUpload增加附加参数
    dedecms5.7 联动类型无法显示
    一些比较隐秘的OJ的网址
    Emacs 配置
    qwq
    233
    [八省联考2018]林克卡特树lct
    [APIO2014]序列分割
  • 原文地址:https://www.cnblogs.com/fish-101/p/10409289.html
Copyright © 2011-2022 走看看