Why does the [removed]true == true == true) produce a syntax error?

前端 未结 3 1885
花落未央
花落未央 2021-02-01 12:11

Ruby:

true == true == true

syntax error, unexpected tEQ

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 12:41

    The first answer is excellent, but just in case it's not completely clear (and people asking why), here are few more examples.


    In C, the == operator is left-to-right associative and boolean is represented as 1 (true) and 0 (false), so the first 1 == 1 evaluates to 1 (true) and then you are evaluating the result of first expression with the second. You can try:

    2 == 2 == 2 // => 0
    

    Which in C, is evaluated as:

    (2 == 2) == 2
    1 == 2 // => 0
    

    In Javascript, similarly to C, == is left to right associative. Let's try with 0 this time (although the same example from C would work as well):

    0 == 0 == 0
    false
    

    Again:

    0 == 0 == 0
    true == 0 // => false
    

    In Ruby == does not have associative properties, ie. it can't be used multiple times in single expression, so that expression can't be evaluated. Why that decision was made is a question for the author of the language. Further, Ruby doesn't define numeric 1 as a boolean, so 1 == true evaluates to false.

    The second answer states there are some "weird" cases in Ruby, but they all evaluate as expected:

    (1 == 1) == 1
    true == 1 # => false
    
    1 == (1 == 1)
    1 == true # => false
    
    1 .== 1 == 1
    (1 == 1) == 1
    true == 1 # => false
    
    false .== false == true
    (false == false) == true
    true == true # => true
    
    false .== true == false
    (false == true) == false
    false == false # => true
    
    true .== false == false
    (true == false) == false
    false == false # => true
    
    false .== false == false
    (false == false) == false
    true == false # => false
    
    true .== true == false
    (true == true) == false
    true == false # => false
    

提交回复
热议问题