1

I need get constant name from this:

class Sex
    Male = 1
    Female = 2
end

But this is perfect variant, can i get constant name at least from this:

class Sex
    self.Male = 1
    self.Female = 2
end

Few details about the problem:

  • You can get a list of methods: Class.methods - Object.methods
  • You can get a list of instance variables: instance_variables.map{|ivar| instance_variable_get ivar}
  • You can get a list of constant names from Module: Module.constants

But i have no idea how I can get class constant names.

  • Your second example is wrong. Do you mean `class Sex; class << self; Male = 1; Female = 2; end; end`? – cremno Sep 12 '15 at 16:57
  • I did not think about this way, but yes it will be like u wrote. Anyway, it is not answer. –  Sep 12 '15 at 17:01
  • The second example isn't defining constants, it's calling methods. – cremno Sep 12 '15 at 17:04

2 Answers2

1
class Sex
  Male = 1
  Female = 2
end

This defines two constants on the Sex class. Sex is an instance of Class and the superclass of Class is Module:

c = Sex.class  # => Class
c.superclass   # => Module

You already know how to get an array of constant names as symbols from a module and since this method is inherited, you can just call it on the Sex class:

Sex.constants  # => [:Male, :Female]

I'm not sure about your second example. Assuming you mean this (read about class << self):

class Sex
  class << self
    Male = 1
    Female = 2
  end
end

This defines two constants on the singleton class of the Sex class. The method Object#singleton_class returns the singleton class of an object. After that methods, instance_variables or constants can be called in the usual way:

Sex.singleton_class.constants  # => [:Male, :Female]
cremno
  • 4,672
  • 1
  • 16
  • 27
1

You can use constants on Class object as well as shown below

class Sex
    Male = 1
    Female = 2
end

p Sex.constants # will return [:Male, :Female]

The reason it will work is Module happens to be base class of Class

p Sex.class.ancestors
#=> [Class, Module, Object, Kernel, BasicObject]
Wand Maker
  • 18,476
  • 8
  • 53
  • 87