Difference between '..' (double-dot) and '…' (triple-dot) in range generation?

前端 未结 5 1560
执笔经年
执笔经年 2020-11-27 14:08

I\'ve just started learning Ruby and Ruby on Rails and came across validation code that uses ranges:

validates_inclusion_of :age, :in => 21..99
validates_         


        
5条回答
  •  伪装坚强ぢ
    2020-11-27 14:48

    a...b excludes the end value, while a..b includes the end value.

    When working with integers, a...b behaves as a..b-1.

    >> (-1...3).to_a
    => [-1, 0, 1, 2]
    
    >> (-1..2).to_a
    => [-1, 0, 1, 2]
    
    >> (-1..2).to_a == (-1...3).to_a
    => true
    

    But really the ranges differ on a real number line.

    >> (-1..2) == (-1...3)
    => false
    

    You can see this when incrementing in fractional steps.

    >> (-1..2).step(0.5).to_a
    => [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]
    
    >> (-1...3).step(0.5).to_a
    => [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5]
    

提交回复
热议问题