Is there a difference between "TRUE" and "true"?

There are two instances of TrueClass , FalseClass and NilClass with different names: one in lowercase and one in upper case. One instance seems to be evaluating another:

 true # => true TRUE # => true true == TRUE # => true 

Is there a difference between the two constants, and if so, what are the differences? If they are the same, which of these constants should be used in my code? Should I write some_value = true or some_value = true ?

+6
source share
3 answers

The difference is that although true is a keyword in Ruby, true is a constant:

 true = 1 # => SyntaxError: Can't assign to true TRUE = false # => warning: already initialized constant TRUE # => false TRUE == true # => false 
+10
source

Not.

 true.object_id # => 20 TRUE.object_id # => 20 true == TRUE # => true 

But use true as the all-caps version is rare and can be confusing.

This is obviously a constant when it is uppercase, but it is a constant that is initialized with the same object reference as true , so it is not completely different. Remember that Ruby variables and constants are just object references. All this is an object.

The same and different as the English words are hard to define. You can argue all day about the meaning of English words. In OOP, we define the concepts of both identity and equality. In this case, true and true same and equal. Therefore, a Ruby equality comparison returns true and why the object identifiers are equal.

So, I think, given that both actual definitions of OOP in this case are the same, we can also say the same thing. But you do not need it, I think.

+7
source

Although there is no practical difference:

 true.class # => TrueClass TRUE.class # => TrueClass 

You have to use

 variable = true 

Uppercase is commonly used for naming constants as such:

 NUMBER_OF_WEEKDAYS = 7 

As mentioned in other answers, there is a trick that I did not mention:

 TRUE == true # => true TRUE = false true == TRUE # => false 
+1
source

All Articles