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

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

Ruby:

true == true == true

syntax error, unexpected tEQ

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

    TL;DR The syntax implies that all 3 values are equal this is not what it does in javascript or C, so by ruby giving a syntax error the door is open for this to be implemented in the future.

    If I understand the question correctly value_a == value_b == value_c should only return true if they are all equal using == as the comparison operater as shown in this method

    # version 1
    def compare_3_values(a, b, c)
      a == b && a == c && b == c
    end
    

    there is another possible expected outcome though. to implement this as shown in the previous answer:

    #version 2
    def compare_3_values(a, b, c)
      (a == b) == c
    end
    

    The results are worlds apart.

    JavaScript always uses version 2 which is pretty useless as the 3rd item is always being compared against true or false (0 or 1 if the 3rd item is an integer) that's why false == false == true returns true.

    The good news is that because ruby gives a syntax error it's the only language that can implement this without breaking everyone's code.

    for any other language it would break so much code that even if it were implemented in a later major version there would need to be a flag/setting to turn this on or off for years to come, hence it will never be worthwhile.

    Some interesting results in Ruby

    false .== false == true
    => true
    
    false .== true == false
    => true
    
    true .== false == false
    => true
    
    false .== false == false
    => false
    
    true .== true == false
    false
    

    And in javascript

    false == false == true
    => true
    
    false == true == false
    => true
    
    true == false == false
    => true
    
    false == false == false
    => false
    
    true == true == false
    => false
    

    Edit tested in C as well, acts similar to JavaScript in that it compares the result of the first two values against the third value

提交回复
热议问题