Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a constant and a variable in Ruby?

Tags:

ruby

So, I'm doing a Ruby course on CodeAcademy and I'm stuck in differentiating the difference between a variable and a class. Can someone please explain the difference to me? I'll give you cookies! ^^. No matter where I look online I can't find any information on this.

like image 736
Alestaire Caines Avatar asked Dec 21 '16 21:12

Alestaire Caines


2 Answers

The idea of constants in Ruby is that they can get a value assigned only once while you can assign a new value to a variable as many times as you want. Now technically, you can assign a new value even to a constant. Ruby will however issue a warning in this case and you should try to avoid this case.

I guess the main point leading to confusion of people new to Ruby is that even values assigned to constants can be modified without a warning (e.g. by adding new elements to an array). References by a constant are no different to variables here in that the reference does not restrict what can be done with the value. The object referenced by either a variable or constant is always independent from that.

In this example, I assign a new array to the ARRAY constant. Later, I can happily change the array by adding a new member to it. The constant is not concerned by this.

ARRAY = []
# => []
ARRAY << :foo
ARRAY
# => [:foo]

The only thing forbidden (or, well, allowed with a warning) is if you try to assign a completely new value to a constant:

ARRAY2 = []
# => []
ARRAY2 = [:bar]
# warning: already initialized constant ARRAY2
ARRAY2
=> [:bar]

As such, it is common practice to immediately freeze values assigned to constants to fully deny any further changes and ensure that the original value is preserved (unless someone assigns a new value):

ARRAY3 = [:foo, :bar].freeze
ARRAY3 << :baz
# RuntimeError: can't modify frozen Array
like image 90
Holger Just Avatar answered Nov 15 '22 04:11

Holger Just


  • A variable can change its value, it can vary.
  • A constant cannot change its value, it is constant.

In Ruby things are a bit more complex though. You can reassign the value of constants, but it will print a warning. This is meant to be used for debugging only and the general principle still applies that constants are meant to be used for values that never change.

like image 41
akuhn Avatar answered Nov 15 '22 05:11

akuhn