Public Static Final for Ruby

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

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

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


josh said…
Man. Good call. I remember spending a good hour googling for this one a few months back. Static methods look similar. Name them like def Classname::method_name and you are golden.
zsong said…
Make it real finial:

That will prevent redefining the constant SolarConstants::MASS_OF_EARTH
Why bother with the module? If we're just trying to get Ruby to have constants exposed in classes, just throwing them into the class is enough to get at them with SolarConstants::MASS_OF_THAT_BLUE_BALL. All these mixins are fun, though... Anyway, thanks and congratulations for showing up so high in Google :)
Anonymous said…
This saved me a lot of time! Thank you so much!

Popular posts from this blog

What's a Good Flog Score?

SICP Wasn’t Written for You

Point Inside a Polygon in Ruby