gpt4 book ai didi

ruby - 使用 float 在 Ruby 中打开范围?

转载 作者:数据小太阳 更新时间:2023-10-29 07:41:08 24 4
gpt4 key购买 nike

是否可以在 ruby​​ 中创建排除一个或两个端点的范围。那么如何处理开闭区间边界的数学概念呢?

例如,我可以定义一个从 1.0 到 10.0 的范围,不包括 1.0

说(用伪 ruby )

range = [1.0...10.0)

range === 1.0
=> false

range === 10.0
=> true

最佳答案

Ruby 中的Range 类只支持封闭和半开(右开)范围。但是,您可以轻松编写自己的代码。

这是 Ruby 中半开范围的示例:

range = 1.0...10.0

range === 1.0
# => true

range === 10.0
# => false

Rubinius 中符合 Ruby 1.9 的 Range 类的总行数是 238 行 Ruby 代码。如果您不需要 open range 类来支持 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

关于ruby - 使用 float 在 Ruby 中打开范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12493335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com