1

Is there any point of using constants instead of methods returning those constants like this?

class Foo
  LETTERS = [:a, :b, :c]
  # and them call it Foo::LETTERS
end

# or 
class Foo
  def self.letters
    [:a, :b, :c]
    # and then call it Foo.letters, more simplier
  end
end

I could see only one advantage of first approach: warning when trying to redefine constant, but it's rare case, I think.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
hedgesky
  • 3,271
  • 1
  • 21
  • 36

1 Answers1

5

Your second approach creates a new array each time the method Foo.letters is called. This, of course, can be fixed by saving the value:

class Foo
  def self.letters
    @letters ||= [:a, :b, :c]
  end
end

Also, there are some changes in behavior when inheriting such a class with each approach (see "How to use an overridden constant in an inheritanced class")

Personally, I don't see how Foo.letters is simpler than Foo::LETTERS - an extra character? I think that constants should be used for constants, and that static methods have their own use-cases...

Community
  • 1
  • 1
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93