Search code examples
rubyblockrubymotion

Access variable inside block


I'm using a certain block in RubyMotion and trying to access an instance variables inside of it which was declared outside. It turns out I can't access the variable from the inside. Is there any obvious solution I'm missing here? Thanks!

Here is the code

@my_var = true

Dispatch::Queue.concurrent.async do
  # can't access @my_var here
end

Solution

  • My guess is that async runs the block with instance_eval, so your instance variable is binding to some other object when used inside the block. If you only need to read the variable, just use a local copy inside the block

    @my_var = true
    my_var = @my_var
    Dispatch::Queue.concurrent.async do
      my_var
    end
    

    or if you have an accessor method

    @my_var = true
    this = self
    Dispatch::Queue.concurrent.async do
      this.my_var
    end