I was implementing a form that includes a hard-coded dropdown for a collection and I was wondering what would be the best solution, I know both ways exposed below work, still I did as follows:
class Example # Options for Example. self.options [ 'Yes', 'No', 'Not sure' ] end end
which is called by Example.options
, but I know it is possible to do as follows as well:
class Example # Options for Example. OPTIONS = [ 'Yes', 'No', 'Not sure' ] end
that would be called with Example::OPTIONS
.
The question is, is any of these the good way or it just doesn't matter at all?
Class constants are useful when you need to declare some constant data (which does not change) within a class. There are two ways to access class constant: Outside the Class: The class constant is accessed by using the class name followed by the scope resolution operator (::) followed by the constant name.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition.
What is a constant in Ruby? A constant is a type of variable which always starts with a capital letter. They can only be defined outside of methods, unless you use metaprogramming. Constants are used for values that aren't supposed to change, but Ruby doesn't prevent you from changing them.
A class constant is a field that is declared with the static and final keywords. As a reminder, the final keyword indicates that the field reference cannot be changed to point to a different value.
The latter is better. If it were a method, a new array and new strings will be created every time it is called, which is a waste of resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With