有没有一种方法可以在红宝石中重新定义[] = + [英] Is there a way to redefine []=+ in ruby

查看:55
本文介绍了有没有一种方法可以在红宝石中重新定义[] = +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a simple DSL (against Redis) and I would like to define []+= myself

我有

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

我想定义

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

但是我的理解是Ruby自动提供[[] =

But my understanding is that Ruby provides the "[]+=" operator automaticallygiven []=

是否有一种方法可以替代此行为 显然,我不希望这样做,因为我无法以管道模式运行此程序

Is there a way to over-ride this behavior Obviously I don't want this because I would not be able to, say, run this in pipeline mode

推荐答案

否,不能在Ruby中重新定义<operator>=.

No, <operator>= can not be redefined in Ruby.

您可以尝试真正看中并将返回值包装在委托给实际值的类中.这样,它们的行为就像实际值一样,但是您可以玩一些技巧,例如使用+.

You can try to get really fancy and wrap your return values in classes that delegate to the actual value. This way, they behave like the actual value, but you can play tricks, for instance with +.

这是一个简单的例子:

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 ...

This is just a starting point. You'll have to be more careful than this, for example by checking the key is the same. In my simplistic example, redis[:foo] = redis[:bar] + 1 would actually be equivalent to redis[:foo] += 1...

这篇关于有没有一种方法可以在红宝石中重新定义[] = +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆