有没有办法在 ruby​​ 中重新定义 []=+

2024-05-07

我正在尝试编写一个简单的 DSL(针对 Redis)并且我想自己定义 []+=

I have

def []=(key,val)
  @redis.zadd(@name,val,key)
end

我想定义

def []+=(key,val)
  @redis.zincrby(@name,val,key)
end

但我的理解是,Ruby 提供了“[]+=”运算符,自动给出 []=

有没有办法克服这种行为 显然我不想要这个,因为我无法在管道模式下运行它


No, <operator>=无法在 Ruby 中重新定义。

您可以尝试变得非常奇特,并将返回值包装在委托给实际值的类中。这样,它们的行为就像实际值一样,但您可以玩一些技巧,例如+.

这是一个简单的例子:

require 'delegate'
module Redis
  class Set
    class Value < SimpleDelegator
      def +(val)
        Increment.new(self, val)
      end
    end

    class Increment < SimpleDelegator
      attr_reader :increment
      def initialize(source, increment)
        super(source.__getobj__ + increment)
        @increment = increment
      end
    end

    def [](key)
      Value.new(@redis.not_sure_what(@name, key))
    end

    def []=(key,val)
      if val.is_a?(Increment)
        @redis.zincrby(@name,val.increment,key)
      else
        @redis.zadd(@name,val,key)
      end
    end
  end
end

这只是一个起点。您必须比这更加小心,例如检查密钥是否相同。在我的简单例子中,redis[:foo] = redis[:bar] + 1实际上相当于redis[:foo] += 1...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法在 ruby​​ 中重新定义 []=+ 的相关文章

随机推荐