2013-10-22 53 views
0

我是Rails的新手,我使用Ruby 1.9.3和Rails 3.0.0。如何在Rails中打印数组?

我想打印在Rails的数组。我怎么做?

例如,我们必须使用print_r在PHP打印数组:

<?php 

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); 
print_r ($a); 

?> 

输出:

<pre> 
Array 
(
    [a] => apple 
    [b] => banana 
    [c] => Array 
     (
      [0] => x 
      [1] => y 
      [2] => z 
     ) 
) 
</pre> 

如何打印在Rails的一个数组?

+8

'<%= debug array%>'或'<%= array.inspect%>' – martincarlin87

回答

10

您可以使用inspect像:

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

或者:

p @a.inspect #"[\"a\", \"b\"]" 
+3

如果我们需要将它呈现给html页面,我们可以使用<%= @ a.inspect%>。 –

2

您需要使用awesome_print宝石。

require 'awesome_print' 

hash = {:a=>1,:b=>2,:c => [1,2,3]} 

ap hash 

输出:

{ 
    :a => 1, 
    :b => 2, 
    :c => [ 
     [0] 1, 
     [1] 2, 
     [2] 3 
    ] 
} 
0

你有几个选择这里。我假设你在ERB模板中这样做。

这将数组转换成YAML,并打印出来在<pre>标签

,这将其打印出来可读的Ruby语法格式包围:

<pre><%= [1,2,3,4].inspect %></pre> 

退房“Debugging Rails Applications “获取更多信息。

0

这取决于你要使用数组什么。

盲目输出的视图,其必须在视图一个数组,你应该使用debuginspect这样的:

<%= @array.inspect() %> 

<%= debug @array %> 

但是,如果你想通过数组进行迭代,或者做像explode()这样的事情,你会更适合使用Ruby数组函数。