Reputation: 7762
I am new to Rails and I am using Ruby version 1.9.3 and Rails version 3.0.0.
I want to print an array in Rails. How do I do that?
For example, we have to use print_r
to print an array in PHP:
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
Output:
<pre>
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
</pre>
How do I print an array in Rails?
Upvotes: 0
Views: 3438
Reputation: 6015
You can use inspect
like:
@a = ['a', 'b']
p @a #['a', 'b']
Or:
p @a.inspect #"[\"a\", \"b\"]"
Upvotes: 11
Reputation: 1036
You've got a couple of options here. I'm assuming you're doing this in an ERB template.
This will convert the array to YAML and print it out surrounded in <pre>
tags
<%= debug [1,2,3,4] %>
And this will print it out formatted in a readable Ruby syntax:
<pre><%= [1,2,3,4].inspect %></pre>
Check out "Debugging Rails Applications" for more info.
Upvotes: 0
Reputation: 76774
It depends on what you want to use the array for.
To blindly output an array in a view, which has to be in a view, you should use debug
and inspect
like this:
<%= @array.inspect() %>
<%= debug @array %>
However, if you want to iterate through an array, or do things like explode()
, you'll be better suited using the Ruby array functions.
Upvotes: 0
Reputation: 118299
You need to use awesome_print
gem.
require 'awesome_print'
hash = {:a=>1,:b=>2,:c => [1,2,3]}
ap hash
output:
{
:a => 1,
:b => 2,
:c => [
[0] 1,
[1] 2,
[2] 3
]
}
Upvotes: 2