views:

843

answers:

7

In PHP you can do:

print_r($var) or vardump($var)

which prints "human-readible" information about variable.

Is there equivalent functions / helpers for those in Ruby / Rails ?

+5  A: 

Try using pp. You will need to require it in scripts (or in irb if your .irbc doesn't already do this):

require 'pp'

Then you can 'PrettyPrint' an object thus:

pp object
Antibaddy
+4  A: 

There's the method inspect which helps. Sometimes calling the to_s method on an object will help (to_s returns a string representation of the object). You can also query methods, local_variables, class_variables, instance_variables, constants and global_variables.

p ['Hello',"G'day",'Bonjour','Hola'].inspect
# >> "[\"Hello\", \"G'day\", \"Bonjour\", \"Hola\"]"

p ['Hello',"G'day",'Bonjour','Hola'].to_s
# >> "HelloG'dayBonjourHola"

p Array.new.methods
# >> ["select", "[]=", "inspect", "compact"...]

monkey = 'baboon'
p local_variables
# >> ["monkey"]

class Something
  def initialize
    @x, @y = 'foo', 'bar'
    @@class_variable = 'gorilla'
  end
end

p Something.class_variables
# >> ["@@class_variable"]

s = Something.new
p s.instance_variables
# >> ["@x", "@y"]

p IO.constants
# >> ["TRUNC", "SEEK_END", "LOCK_SH"...]

p global_variables
# >> ["$-d", "$\"", "$$", "$<", "$_", "$-K"...]
dylanfm
+6  A: 

Instead of requiring 'pp' and using pp, you can simply do

p object

Tested example

require 'pp'

class A
  def initialize
    @a = 'somevar'
    @b = [1,2,3]
    @c = {'var' => 'val'}
  end
end

a = A.new
pp a # Gives -> #<A:0x2c6d048 @a="somevar", @b=[1, 2, 3], @c={"var"=>"val"}>
p a # Gives -> #<A:0x2c6d048 @a="somevar", @b=[1, 2, 3], @c={"var"=>"val"}>. No need to require 'pp'
Chirantan
+8  A: 

In Rails templates you can do

<%= debug an_object %>

and it will do nice HTML PRE output.

Honza
+2  A: 

Check out the guide for debugging rails: http://guides.rubyonrails.com/debugging_rails_applications.html

hints: script/console is great to try stuff in the context of your app script/server --debugger to start the server with a debugger turned on, you can then use 'debug' in your code to break into an interactive shell

Kevin Davis
A: 

Guess I'm a little late to this, but what about logger.info [debug|warning]? Use this from Controllers and Models. It will show up in your log files (development.log when in dev mode); and the above mentioned <%= debug("str: " + str) %> for views.

These aren't exact answers to your questions but you can also use script/console to load your rails app in to an interactive session.

Lastly, you can place debugger in a line of your rails application and the browser will "hang" when your app executes this line and you'll be able to be in a debug session from the exact line your placed your debugger in the source code.

Rob
A: 

One approach I lean on a lot is this:

logger.debug "OBJECT: #{an_object.to_yaml}"

Easy to read, although it can get a little unwieldy for large objects.