# Printing variable name and value

**URL:** <https://www.ruby-forum.com/t/printing-variable-name-and-value/121254>\
**Category:** Ruby\
**Created:** [November 26, 2007, 4:55am UTC](https://www.ruby-forum.com/t/printing-variable-name-and-value/121254 "2007-11-26T04:55:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![adambeazley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@adambeazley](https://www.ruby-forum.com/u/adambeazley)\
**Post date:** [November 26, 2007, 4:55am UTC](https://www.ruby-forum.com/t/printing-variable-name-and-value/121254/1 "2007-11-26T04:55:09Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![adambeazley](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/5f9b8f/32.png) [@adambeazley](https://www.ruby-forum.com/u/adambeazley)\
**Post date:** [November 26, 2007, 5:45am UTC](https://www.ruby-forum.com/t/printing-variable-name-and-value/121254/2 "2007-11-26T05:45:57Z")

</div>

On Nov 25, 9:54 pm, Adam B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> arr = eval(label.to_s, bind)
> 
> ```
> 
> when “String”  
> y = “aasdf”  
> pprint :y, binding
> 
> x = [1, 2, 3]  
> pprint :x, binding
> 
> z = {‘a’ =\> 1, ‘b’ =\> 3}  
> pprint :z, binding

Check the group archives as this was discussed recently. The example  
you gave could be written as:

def pprint(label, bind)  
puts “#{label} is #{eval(label.to\_s, bind).inspect}”  
end

Jeremy
