gpt4 book ai didi

ruby - 有没有一种优雅的方法可以排除范围的第一个值?

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

假设我的范围是 0 到 10:

range = 0...10

三个点表示排除最后一个值 (10):

range.include? 10
=> false

现在,是否有类似且优雅的方法来排除第一个值?
对于上面的示例,这意味着包括所有更大的值(>不是 >=)小于 0 且小于 10。

最佳答案

我有两个建议给你,它们不是很理想,但它们是我能想到的最好的。

首先,您可以在 Range 类上定义一个新方法来执行您描述的操作。它看起来像这样:

class Range
def have?(x)
if x == self.begin
false
else
include?(x)
end
end
end

p (0..10).have?(0) #=> false
p (0..10).have?(0.00001) #=> true

我不知道,我只是用了“include”的同义词作为方法名,也许你能想到更好的东西。但这就是想法。

然后您可以做一些更精细的事情,并在 Range 类上定义一个方法,将一个范围标记为您要排除其起始值的范围,然后更改 Range 的 include?检查该标记的方法。

class Range
def exclude_begin
@exclude_begin = true
self
end

alias_method :original_include?, :include?
def include?(x)
return false if x == self.begin && instance_variable_defined?(:@exclude_begin)
original_include?(x)
end

alias_method :===, :include?
alias_method :member?, :include?
end

p (0..10).include?(0) #=> true
p (0..10).include?(0.00001) #=> true
p (0..10).exclude_begin.include?(0) #=> false
p (0..10).exclude_begin.include?(0.00001) #=> true

同样,您可能想要一个比 exclude_begin 更好(更优雅?)的方法名称,我之所以选择它是因为它与 Range 的 exclude_end? 方法一致。

编辑:我为您准备了另一个问题,只是因为我觉得这个问题很有趣。 :P 这仅适用于最新版本的 Ruby 1.9,但将允许以下语法:

(0.exclude..10).include? 0       #=> false
(0.exclude..10).include? 0.00001 #=> true

它使用与我的第二个建议相同的想法,但将“排除标记”存储在数字而不是范围中。我必须使用 Ruby 1.9 的 SimpleDelegator 来完成这个(数字本身不能有实例变量或任何东西),这就是它在早期版本的 Ruby 中不起作用的原因。

require "delegate"

class Numeric
def exclude
o = SimpleDelegator.new(self)
def o.exclude_this?() true end
o
end
end

class Range
alias_method :original_include?, :include?
def include?(x)
return false if x == self.begin &&
self.begin.respond_to?(:exclude_this?) &&
self.begin.exclude_this?
original_include?(x)
end

alias_method :===, :include?
alias_method :member?, :include?
end

关于ruby - 有没有一种优雅的方法可以排除范围的第一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3358788/

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