Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants or class variables in ruby?

I've been programming in Ruby for a few months now, and I'm wondering when it is appropriate to use constants over class variables and vice versa. (I'm working in Rails, thinking about constants in models).

class Category   TYPES = %w(listing event business).freeze end 

OR

class Category   @@types = %w(listing event business).freeze   cattr_reader :types end 

Are there circumstances where one is preferable to another? Or is it just a matter of taste/style?

like image 392
Ben Crouse Avatar asked Dec 22 '08 22:12

Ben Crouse


People also ask

What are constants 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 variable in Ruby?

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.

What is the difference between class variable and instance variable in Ruby?

What is the difference between class variables and class instance variables? The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.


1 Answers

The main thing is that by using the CONSTANT notation, you're making it clear to the reader. the lower case, frozen string gives the impression is might be settable, forcing someone to go back and read the RDoc.

like image 147
Charlie Martin Avatar answered Sep 30 '22 01:09

Charlie Martin