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

后端 未结 3 1714
野趣味
野趣味 2021-01-19 07:05

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?

3条回答
  •  青春惊慌失措
    2021-01-19 07:32

    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
    

提交回复
热议问题