You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby事件块中引用当前实例(this)对象?

在Ruby事件块中引用当前类实例(类似其他语言的this)

在Ruby里,要在WebSocket这类事件处理块里拿到当前Proxy类的实例(就像其他语言里的this),核心是要解决块的上下文问题——因为块执行的时候,self会切换成触发事件的对象(比如这里的WebSocket实例),而不是你的Proxy实例。下面给你两种常用的解决办法:

方法1:保存当前实例到外部变量(最直观)

在块定义之前,把当前Proxy实例(也就是self)赋值给一个变量,利用Ruby闭包能访问外部作用域变量的特性,在块内部通过这个变量来引用实例:

module WebsocketClient
  class Proxy
    attr_accessor :worker_id, :websocket_url, :websocket

    def initialize(worker_id, websocket_url)
      @worker_id = worker_id
      @websocket_url = websocket_url
    end

    def connect
      # 保存当前Proxy实例到变量,供块内部使用
      current_proxy = self
      @websocket = WebSocket::Client::Simple.connect @websocket_url
      puts "websocket: #{@websocket}"
      @websocket.on :open do |ws|
        begin
          puts "called on open event #{ws}, proxy instance: #{current_proxy}."
          # 现在可以通过current_proxy访问实例属性和方法
          puts "Worker ID from proxy: #{current_proxy.worker_id}"
          # 发送认证消息...
        end
      end
    end
  end
end

方法2:使用instance_exec切换块的上下文

如果你希望在块内部直接用self指代Proxy实例,可以用instance_exec方法,它会把块的执行上下文切换到指定对象,同时还能传递参数:

def connect
  @websocket = WebSocket::Client::Simple.connect @websocket_url
  puts "websocket: #{@websocket}"
  @websocket.on :open do |ws|
    # 切换块的上下文到当前Proxy实例,并传递ws参数
    self.instance_exec(ws) do |ws|
      puts "called on open event #{ws}, this proxy: #{self}."
      # 这里的self就是Proxy实例,可以直接访问实例属性
      puts "Worker ID: #{@worker_id}"
      # 发送认证消息...
    end
  end
end

补充:为什么原来的代码里@websocket可能不符合预期?

你原来代码里的@websocket在块内部,其实是访问块执行时当前self的实例变量(也就是WebSocket实例的@websocket,大概率不存在),而不是Proxy实例的@websocket。所以必须通过上述方法显式引用Proxy实例,才能正确访问它的属性和方法。

内容的提问来源于stack exchange,提问作者satish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:43:40