Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Module | constants

概要

Module.constants -> [Symbol]

詳細

呼び出した時に参照可能な定数名の配列を返却。

サンプルコード
require 'tbpgr_utils'

class Hoge
  CONST1 = 1
  CONST2 = "hoge"
  class InnerHoge
    INNER_CONST = 1
  end
  def check_module_const(const_name)
    Module.constants.include?(:CONST1)
  end
end


bulk_puts_eval binding, <<-EOS
Module.constants.size
Module.constants.first
Module.constants.last
Module.constants.include?(:CONST1)
Module.constants.include?(:CONST2)
Module.constants.include?(:INNER_CONST)
Hoge.new.check_module_const(:CONST1)
Hoge.new.check_module_const(:CONST2)
Hoge.new.check_module_const(:INNER_CONST)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

Module.constants.size                     # => 137
Module.constants.first                    # => :Object
Module.constants.last                     # => :RUBYGEMS_ACTIVATION_MONITOR
Module.constants.include?(:CONST1)        # => false
Module.constants.include?(:CONST2)        # => false
Module.constants.include?(:INNER_CONST)   # => false
Hoge.new.check_module_const(:CONST1)      # => true
Hoge.new.check_module_const(:CONST2)      # => true
Hoge.new.check_module_const(:INNER_CONST) # => true