Difference between “and” and && in Ruby?

前端 未结 7 1344
别跟我提以往
别跟我提以往 2020-11-22 09:28

What is the difference between the && and and operators in Ruby?

7条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:35

    The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:

    foo = :foo
    bar = nil
    
    a = foo and bar
    # => nil
    a
    # => :foo
    
    a = foo && bar
    # => nil
    a
    # => nil
    
    a = (foo and bar)
    # => nil
    a
    # => nil
    
    (a = foo) && bar
    # => nil
    a
    # => :foo
    

    The same thing works for || and or.

提交回复
热议问题