Ruby constants defined in arrays and hashes can be accessed via the class

1 min read

  • TIL
  • Rails

Published on January 31, 2025

If you've worked with ruby, you're familiar with defining constants in classes using the standard approach and accessing them using ::

class FormField
  VALID_OPTION = 'valid'
  INVALID_OPTION = 'invalid'
end

puts FormField::VALID_OPTION
puts FormField::INVALID_OPTION

However, today I learned an interesting ruby quirk: you can define constants within other data structures in your class such as arrays or hashes, and they'll still be accessible through the class namespace. Here is what I mean:

class FormField
  OPTIONS = [
    VALID_OPTION = "valid",
    INVALID_OPTION = "invalid"
  ].freeze
end

puts FormField::VALID_OPTION
puts FormField::INVALID_OPTION


In the above case, even though the constants VALID_OPTIONS and INVALID_OPTION are defined inside of an array, OPTIONS in this case, we can still access the constants via FormField::VALID_OPTION andFormField::INVALID_OPTION