What is the difference between constant and variable in Ruby?

So, I am doing a Ruby course in CodeAcademy, and I am fixated on the difference between a variable and a class. Can someone please explain the difference to me? I will give you cookies! ^^. No matter where I look online, I can not find any information about this.

+4
source share
3 answers

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

, , Ruby, , , , (, ). , , . , , , .

ARRAY. , . .

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

, (, , ), - :

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

, , , ( - ):

ARRAY3 = [:foo, :bar].freeze
ARRAY3 << :baz
# RuntimeError: can't modify frozen Array
+4
  • , .
  • , .

Ruby . , . , , , .

+1

Ruby - , ; . , . :

NAME = "Fred"
NAME = "Barney"    # => Warning: Already initialized constant NAME

- , ; :

name = "Fred"
name = "Barney"    # => No warning

When creating a class, a constant is created with the same name as the class; this constant is associated with the class:

class Foo
end

This is equivalent to this code, which creates a new anonymous class and assigns it to the constant Foo:

Foo = Class.new do
end

You can reassign the constant identifier Foo as you can with any other constant, but of course you shouldn't, and you will still get a warning:

Foo = 123    # => Already initialized constant Foo
0
source

Source: https://habr.com/ru/post/1664485/


All Articles