From: Adam Bender Date: 2007-11-26T12:54:44+09:00 Subject: Printing variable name and value ------=_Part_36848_10142349.1196049286194 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi, I want a function that will pretty-print the name and value of a variable, so I can avoid writing things like: puts "x is #{x}" Ideally, I would just be able to pass the variable, or at most a label, to a function, and have it do this for me. I wrote something that almost works; I have to pass the current binding as well. Is there a way to avoid this? Is there a better way to do what I've done below? Thanks, Adam =============================== #!/usr/bin/ruby def pprint(label, bind) typ = eval(label.to_s, bind).class.name case typ when "Array" arr = eval(label.to_s, bind) puts label.to_s + " is [" + arr.join(", ") + "]" when "Hash" hash = eval(label.to_s, bind) puts label.to_s + " is {" + hash.collect { |k, v| "#{k} => #{v}" }.join(", ") + "}" when "Fixnum" puts label.to_s + " is " + eval(label.to_s, bind).to_s when "String" puts label.to_s + " is " + eval(label.to_s, bind) else puts "unknown type: #{typ}" end end a = 3 pprint :a, binding y = "aasdf" pprint :y, binding x = [1, 2, 3] pprint :x, binding z = {'a' => 1, 'b' => 3} pprint :z, binding ------=_Part_36848_10142349.1196049286194--