Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class method vs constant in Ruby/Rails

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?

like image 364
Genís Avatar asked Apr 09 '13 13:04

Genís


People also ask

What is the purpose of the class & method constant?

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.

What are class methods in Rails?

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?

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.

What is a class constant?

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.


1 Answers

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.

like image 119
sawa Avatar answered Oct 13 '22 21:10

sawa