Is there an analogue of python vars () method in Ruby?

Python has a vars () method that returns a dictionary of local variable names in the form of keys and their values, so you can do something like this:

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

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

local_variables.inject({}) {|res,var| res[var] = eval(var.to_s); res}
+3
source share
2 answers

- , . , , . , , - , - , . ( , vars ) .

#!/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)
+1

, ,

"#{a} #{b}"

, vars()?

+1

Source: https://habr.com/ru/post/1761137/


All Articles