Is there an analog of Python's vars() method in Ruby?
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}
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)
The ruby equivalent of what you are doing is just
"#{a} #{b}"
Is there another reason you need vars()
?
精彩评论