Public Static Final for Ruby

30 May 2007

When I first got into Ruby awhile back I found that I wanted to do something like I used to in Java:

public static final String BLUE = “blue”;

But darned if I could get the internet to tell me how, so here I am giving back to the community:

in solar_constants.rb:

module SolarConstants
MASS_OF_EARTH = 5.98e24
end

in some other file:

require ‘solar_constants’
puts SolarConstants::MASS_OF_EARTH

or you can:

require ‘solar_constants’
class Gravity
include SolarConstants

def print_mass_of_earth
puts MASS_OF_EARTH
end
end

This being Ruby you can, of course, redefine a constant. But you will get a stern warning.