设为首页 加入收藏

TOP

ruby module extend self vs module_funciton
2017-10-09 13:49:38 】 浏览:5914
Tags:ruby module extend self module_funciton

最近学习ruby过程中,extend self 跟 module_function 傻傻分不清楚,查资料后明白之间的差别,虽记录之,原文地址 github

module A
  extend self

  def a
    puts 'In a'
  end

  private
  def b
    puts 'In b'
  end
end


module B
  def c
    puts 'In c'
  end
  private
  def d
    puts 'In d'
  end
  module_function :c, :d
end

A.a => In a
A.b => NoMethodError: private method b called for A:Module
B.c => In c
B.d => In d


class O
  include A
  include B
end
o = O.new => #<O:0x007f90ed2cdb18>
o.a => In a
o.b => NoMethodError: private method b called for #<O:0x007f90ed2cdb18>
o.c => NoMethodError: private method c called for #<O:0x007f90ed2cdb18>
o.d => NoMethodError: private method d called for #<O:0x007f90ed2cdb18>

总结:module_function 会将module自身的方法变为public(即使方法本身声明为private), mixin之后所有的方法都变为实例的私有方法.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇self_vs_default_definee_vs_rece.. 下一篇ruby之gem install

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目