@instance_variable在红宝石块内不可用? [英] @instance_variable not available inside a ruby block?

查看:61
本文介绍了@instance_variable在红宝石块内不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码:

def index
  @q = ""
  @q = params[:search][:q] if params[:search]
  q = @q
  @search = Sunspot.search(User) do
    keywords q
  end
  @users = @search.results
end

如果使用@q而不是q,则搜索始终返回空查询(")的结果.为什么是这样? @q变量对do ... end块不可用吗?

If @q is used instead of q, the search always returns results for an empty query (""). Why is this? Is the @q variable unavailable to the do...end block?

推荐答案

这取决于如何调用该块.如果使用yield关键字或Proc#call方法调用它,则可以在块中使用实例变量.如果使用Object#instance_evalModule#class_eval调用它,则块的上下文将被更改,并且您将无法访问实例变量.

It depends on how the block is being called. If it is called using the yield keyword or the Proc#call method, then you'll be able to use your instance variables in the block. If it's called using Object#instance_eval or Module#class_eval then the context of the block will be changed and you won't be able to access your instance variables.

@x = "Outside the class"

class Test
  def initialize
    @x = "Inside the class"
  end

  def a(&block)
    block.call
  end

  def b(&block)
    self.instance_eval(&block)
  end
end

Test.new.a { @x } #=> "Outside the class"
Test.new.b { @x } #=> "Inside the class"

在您的情况下,看来Sunspot.search正在使用instance_eval在不同的上下文中调用您的块,因为该块需要轻松访问该keywords方法.

In your case, it looks like Sunspot.search is calling your block in a different context using instance_eval, because the block needs easy access to that keywords method.

这篇关于@instance_variable在红宝石块内不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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