Ruby - print the variable name and then its value
Sure it is possible!
My solution tests the var by Object#object_id identity: http://codepad.org/V7TXRxmL
It's crippled in the binding passing style ...
Although it works just for local vars yet, it can be easily be made "universal" adding use of the other scope-variable-listing methods like instance_variables
etc.
# the function must be defined in such a place # ... so as to "catch" the binding of the vars ... cheesy# otherwise we're kinda stuck with the extra param on the caller@_binding = bindingdef write_pair(p, b = @_binding) eval(" local_variables.each do |v| if eval(v.to_s + \".object_id\") == " + p.object_id.to_s + " puts v.to_s + ': ' + \"" + p.to_s + "\" end end " , b)end# if the binding is an issue just do here:# write_pair = lambda { |p| write_pair(p, binding) }# just some test vars to make sure it worksusername1 = "tyndall"username = "tyndall"username3 = "tyndall"# the result:write_pair(username)# username: tyndall
If it's possible for you to use a symbol instead of the variable name, you could do something like this:
def wp (s, &b) puts "#{s} = #{eval(s.to_s, b.binding)}"end
In use:
irb(main):001:0> def wp (s, &b)irb(main):002:1> puts "#{s} = #{eval(s.to_s, b.binding)}"irb(main):003:1> end=> nilirb(main):004:0> var = 3=> 3irb(main):005:0> wp(:var) {}var = 3
Note that you must pass the empty block {}
to the method or it cannot get the binding to evaluate the symbol.
You can't actually get a variable's name in Ruby. But you could do something like this:
data = {"username" => "tyndall"}
Or even,
username = "tyndall"data = {"username", "password", "favorite_color"}data.each { |param| value = eval(param) puts "#{param}: #{value}"}