easy and clean puts in ruby

184 views Asked by At

I have very often the situation, that i want to Debug something in Ruby. Then i have an output to the console with "puts".

Following example:

Testvariable = 4
puts Testvariable

The output is of course:

4

Now i have a lot of outputs and therefore i write very often something like this:

Testvariable = 4
puts "Testvariable= " + Testvariable

The output is then:

Testvariable= 4

Now this was a very easy case but i hope that it shows what my question is. Does a possibility like this exist???

Testvariable = 4
prettyputs Testvariable

and that the output is directly

Testvariable = 4

I hope you do understand, what my "problem" is? Of course it isnt a lot of work to write the complete string down, but i just want to know if there is a fast and easy possibility?

2

There are 2 answers

3
Lee Hambley On

There's a gem called "ap" awesome_print which does more or less what you want.

The case you listed here doesn't really do the question justice, and probably if you are "puts"ing things, you might want to learn more about debugging and testing tools.

From the AP documentation, consider the following:

data = [ false, 42, %w(forty two), { :now => Time.now, :class => Time.now.class, :distance => 42e42 } ]

Printing this with Ruby's builtin puts would be a mess, but AP prints the following:

$ ruby 1.rb
[
    [0] false,
    [1] 42,
    [2] [
        [0] "forty",
        [1] "two"
    ],
    [3] {
           :class => Time < Object,
             :now => Fri Apr 02 19:55:53 -0700 2010,
        :distance => 4.2e+43
    }
]

I realise that's not exactly what you want, but perhaps the following is equally useful:

puts TestVariable.inspect

since you named it uppercase, I'm going to assume it's a class or a constant, and you want to see it's type, which .inspect will do for you.

2
tomsoft On

This is duplicate to: Ruby: getting variable name

In short: you can not get the name of a variable, but you can put a string or a symbol with the name of the variable you want to display

def prettyputs(symb, the_binding)
  var_name  = symb.to_s
  var_value = eval(var_name, the_binding)
  puts "#{var_name} = #{var_value.inspect}"
end

toto=1
prettyputs "toto",binding

or

prettyputs :toto,binding