Envious about PHP’s variables variable feature? Now you too can use it in your ruby code. Try pasting this in your irb.

class VariableVariable

  instance_methods.each { |m| undef_method m unless m =~ /^__/ }

  def initialize(name, bind)
    @variable = name
    @bind = bind
  end
  
  def ~
    v = eval(@variable, @bind)
    if v.instance_of? String
      VariableVariable.new(v, @bind)
    else
      v
    end
  end
  
  def method_missing(symbol, *args, &block)
    @variable.__send__(symbol, *args, &block)
  end

end

a = VariableVariable.new('b', binding)
c = 'a'
b = 'c'
a
~a
~~a
~~~a
Be Sociable, Share!