使用浮点数在Ruby中打开范围?

mat*_*ald 3 ruby

是否可以在ruby中创建排除一个或两个端点的范围.那么处理开放和封闭区间边界的数学概念?

例如,我可以定义1.0到10.0之间的范围,不包括1.0

说(假伪红宝石)

range = [1.0...10.0)

range === 1.0
=> false

range === 10.0
=> true
Run Code Online (Sandbox Code Playgroud)

Jör*_*tag 7

RangeRuby中的类仅支持闭合和半开(右开)范围.但是,您可以轻松编写自己的.

这是Ruby中半开放范围的一个例子:

range = 1.0...10.0

range === 1.0
# => true

range === 10.0
# => false
Run Code Online (Sandbox Code Playgroud)

RangeRubinius中Ruby 1.9兼容类的总行数是238行​​Ruby代码.如果你不需要你的开放范围类来支持Ruby语言规范的每个皱纹,角落情况,特殊情况,特性,向后兼容性怪癖等等,那么你可以获得更多的东西.

如果你真的只需要测试包含,那么这样的东西就足够了:

class OpenRange
  attr_reader :first, :last

  def initialize(first, last, exclusion = {})
    exclusion = { first: false, last: false }.merge(exclusion)
    @first, @last, @first_exclusive, @last_exclusive = first, last, exclusion[:first], exclusion[:last]
  end

  def first_exclusive?; @first_exclusive end
  def last_exclusive?;  @last_exclusive  end

  def include?(other)
    case [first_exclusive?, last_exclusive?]
    when [true,  true]
      first <  other && other <  last
    when [true,  false]
      first <  other && other <= last
    when [false, true]
      first <= other && other <  last
    when [false, false]
      first <= other && other <= last
    end
  end

  alias_method :===, :include?

  def to_s
    "#{if first_exclusive? then '(' else '[' end}#@first...#@last#{if last_exclusive? then ')' else ']' end}"
  end

  alias_method :inspect, :to_s
end
Run Code Online (Sandbox Code Playgroud)


sai*_*ala 5

您可以使用排除范围的最右边的元素...。见下面的例子

(1..10).to_a # an array of numbers from 1 to 10 - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(1...10).to_a # an array of numbers from 1 to 9 - [1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)