tags:

views:

110

answers:

3

Essentially I'm wondering if the following can be done in Ruby.

So for example:

def bar(symbol) 
  # magic code goes here, it outputs "a = 100" 
end

def foo
  a = 100 
  bar(:a) 
end
+2  A: 

Check article out Variable Bindings in Ruby

class Reference
  def initialize(var_name, vars)
    @getter = eval "lambda { #{var_name} }", vars
    @setter = eval "lambda { |v| #{var_name} = v }", vars
  end
  def value
    @getter.call
  end
  def value=(new_value)
    @setter.call(new_value)
  end
end

def ref(&block)
  Reference.new(block.call, block.binding)
end

def bar(ref)
  # magic code goes here, it outputs "a = 100" 
  p ref.value
end

def foo
  a = 100 
  bar(ref{:a}) 
end

foo
neoneye
+1 looks very interesting, I wonder if this can be done without the block though ...
Sam Saffron
I don't think it can be done without the block in ruby 1.8.x. I'm not familiar with ruby 1.9.x, so things may be different there.
neoneye
+2  A: 

You have to pass foo's context to bar:

def foo
  a = 100
  bar(:a, binding)
end
def bar(sym, b)
  puts "#{sym} is #{eval(sym.to_s, b)}"
end
glenn jackman
+1  A: 

There is no built-in way to get a callers binding in Ruby. (not in 1.8.X or 1.9.X)

The caller method only returns strings which are of little use. The following code would be a good start for patch that could give you the facility.

There is an additional hacky way to get this going using set_trace_func but the performance hit would be huge and the solution is very fragile.

Sam Saffron
here's an example of the fragile way to use set_trace_func to do so : http://stackoverflow.com/questions/1314592/how-can-i-get-the-binding-from-methodmissing/1315612#1315612
rampion