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

后端 未结 3 1671
野趣味
野趣味 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:30

    In Ruby, a constant is an identifier that starts with a capital letter; it is intended to be assigned only once. You can reassign a constant, but you should not. Doing so will generate a warning:

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

    A variable is an identifier that does not start with a capital letter; it may be assigned to more than once:

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

    When you create a class, a constant is created with the same name as the class; that constant is bound to 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 the warning:

    Foo = 123    # => Already initialized constant Foo
    

提交回复
热议问题