gpt4 book ai didi

ruby - 如何检测 Ruby 对象何时位于比较的右侧?

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

我想在 Ruby 中创建一个对象,它可以在访问时延迟执行一些代码,例如检查或比较时。使用 method_missing(将处理 object > 5)拦截消息很容易,但这并不涵盖所有访问对象的尝试。

举例说明:

class Proxy
def initialize(obj)
@object = obj
end

def do_something
self
end

def do_something_else
self
end

def method_missing(msg, *args)
puts "I'm here #{msg}"
# Do something here
@object.send(msg, *args)
end
end

用法:

proxy = Proxy.new(5)
proxy.do_something.do_something_else

proxy > 2
# I'm here >
# true

2 > proxy
# ArgumentError: comparison of Fixnum with Proxy failed

我想知道是否有 Proxy 的实现使得 2 实际上看到了 5 而不是对象。

最佳答案

不,您不能“检测 Ruby 对象何时位于比较的右侧”。我将从中推断出(希望是正确的)您实际上试图解决的问题是如何使用右侧的 Ruby 对象与不同类型的对象进行比较。

答案是定义一个coerce方法。当对象位于比较运算符的右侧而“不兼容”对象位于左侧时,将自动调用此方法。 LHS 对象将作为参数提供,预计会返回一个包含两个元素的数组: 兼容的"new"LHS 和 RHS 值。使用您的代理示例:

class Proxy
def initialize(obj)
@object = obj
end

def coerce(other)
if other.is_a?(Fixnum)
return [ other, @object.to_i ]
end
super
end
end

proxy = Proxy.new(5)

2 > proxy
# => false

当然,如果您希望 Proxy 类能够“包装” Fixnums 以外的值,您的 coerce 方法可能会更复杂。例如,如果 @object 是一个 String 而 other 是一个 Float,你会怎么做?

当然,这仅在对象为 RHS 时处理。要使其也像 LHS 一样工作,您需要使用 Comparable混入。

关于ruby - 如何检测 Ruby 对象何时位于比较的右侧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230962/

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