Module.private_constant做什么?有没有办法只列出私有常量? [英] What does Module.private_constant do? Is there a way to list only private constants?

查看:89
本文介绍了Module.private_constant做什么?有没有办法只列出私有常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Ruby 1.9.3开始,我们可以创建私有常量:

Starting in Ruby 1.9.3, we can create private constants:

module M
  class C; end
  private_constant :C
end

是否有关于此内容的良好文档有吗有没有一种方法可以获取仅私有常量的名称,类似于调用常量

Is there a good documentation about what this does? Is there a way to get the names of only private constants similar to calling constants

推荐答案

从Ruby 2.1开始,而 Module#constants 仅包含公共常量,如果您设置 inherit = false ,您还将获得私有常量。因此,如果您在 constants(false)中找到一个常量,但在 constants 中找不到一个常量(并且您不关心继承的常量),这可能是一种或多或少可靠的判断它是否私有的方法。

As of Ruby 2.1, while Module#constants includes only public constants, if you set inherit=false, you will get private constants as well. So if you find a constant in constants(false) but not in constants (and you don't care about inherited constants), that might be a more or less reliable way to tell if it's private.

class Module
  def private_constants
    constants(false) - constants
  end
end

module Foo
  X = 1
  Y = 2
  private_constant :Y
end

puts "Foo.constants = #{Foo.constants}"
puts "Foo.constants(false) = #{Foo.constants(false)}"
puts "Foo.private_constants = #{Foo.private_constants}"

# => Foo.constants = [:X]
# => Foo.constants(false) = [:X, :Y]
# => Foo.private_constants = [:Y]

这是没有记载的,我不确定这是否是故意的,但根据经验可以。我会用单元测试来支持它。

This is undocumented, and I'm not sure if it's intentional, but empirically it works. I would back it up with unit tests.

更新:看起来这是< a href = https://bugs.ruby-lang.org/issues/12345 rel = nofollow> Ruby中的错误,并且在以后的版本中可能会消失。

Update: It looks like this is a bug in Ruby, and may disappear in a future version.

这篇关于Module.private_constant做什么?有没有办法只列出私有常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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