0

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?

1
  • 8
    <%= debug array %> or <%= array.inspect %> Commented Oct 22, 2013 at 14:13

4 Answers 4

11

You can use inspect like:

@a = ['a', 'b'] p @a #['a', 'b'] 

Or:

p @a.inspect #"[\"a\", \"b\"]" 
Sign up to request clarification or add additional context in comments.

1 Comment

We can use <%= @a.inspect %> if we need to render it to a html page.
2

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 ] } 

Comments

0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.