3

In Python there is vars() method which returns a dictionary of names of local variables as keys, and their values, so it is possible to do something like this:

a = 1
b = 2
"%(a)s %(b)s" % vars()

Is there an analog of vars() in Ruby? The closest construct I can think of is

local_variables.inject({}) {|res,var| res[var] = eval(var.to_s); res}
dimus
  • 7,852
  • 10
  • 40
  • 51

2 Answers2

1

The ruby equivalent of what you are doing is just

"#{a} #{b}"

Is there another reason you need vars()?

John La Rooy
  • 281,034
  • 50
  • 354
  • 495
1

You could implement it something like this, but it's not very pretty. And as gnibbler pointed out, it's just easier to use interpolation. About the only advantage I see to doing something like this is if the format string formats the same values multiple times. And even then, it would probably be easier to use a custom hash (instead of dumping vars into the formatter), or abstracting it into a method.

#!/usr/bin/env ruby

module Kernel
  def vars(b)
    Hash[
      (b.eval('local_variables')-[:_]).
      map{|v| [v,b.eval(v.to_s)]}
    ]
  end
end

a = 10
puts vars(binding)
AboutRuby
  • 7,806
  • 2
  • 25
  • 20