Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Ruby、rails3中创建数组_Ruby On Rails_Ruby_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails 在Ruby、rails3中创建数组

Ruby on rails 在Ruby、rails3中创建数组,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我试图在我的应用程序上制作一些图表,所以我开始使用 它使用数组来输入数据,所以我尝试用ruby创建一些数据数组,然后用javascript打印出来。 i、 e.@array\u example=[1,2,3,4,5]在打印时不起作用,但@array\u example=“[1,2,3,4,5]”可以起作用 无论如何,我的第一个问题是,如果我有: <% @chart_posts = Post.where(:user_id => @profile.user.id) %> @pro

我试图在我的应用程序上制作一些图表,所以我开始使用

它使用数组来输入数据,所以我尝试用ruby创建一些数据数组,然后用javascript打印出来。
i、 e.
@array\u example=[1,2,3,4,5]
在打印时不起作用,但
@array\u example=“[1,2,3,4,5]”
可以起作用

无论如何,我的第一个问题是,如果我有:

<% @chart_posts = Post.where(:user_id => @profile.user.id) %>
@profile.user.id)%%>
使用此数据创建数组的好方法是什么(如果我想要数组中每个帖子的id,以及在处创建的第二个带有
的数组)

为了更清楚一点,最终阵列需要在打印时看起来像一个阵列。

i、 e.它周围必须有
[
,并且
,在每个项目之间。

我不太清楚您的最终数组应该是什么样子,但我认为
map
应该能满足您的需要

ids = @chart_posts.map(&:id) 
# => [1,2,3,4]

created_ats = @chart_posts.map(&:created_at) 
# => [timestamp,timestamp,timestamp,timestamp]
您还可以将其与map组合成单个2D阵列:

array = @chart_posts.map {|post| [post.id, post.created_at]} 
# => [[1, timestamp],[2,timestamp]]

看起来像grose php hackery

但是,加入上面这些人所说的,返回一些字符串:

id_array_string = @chart_posts.map(&:id).inspect 
# => "[1,2,3,4]"

timestamp_array_string = @chart_posts.map(&:created_at).inspect

# => "[timestamp,timestamp,timestamp]"

为了“看起来像一个数组”,如果你直接将它嵌入javascript,你可以使用
数组。为了确保所有字符串都被转义,你可以使用
数组。检查
-它似乎是为了让人可读的输出。注:因为它看起来像你的Post模型
属于:user
而user模型
有y:posts
,您可以改为编写
@profile.user.posts
而不是Post.where子句。