Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating arrays in Ruby, rails3

I'm trying to make some charts on my app, and so I've started using http://www.jqplot.com/index.php

It uses arrays to input the data, so I'm trying to create some arrays of my data in ruby, that I can then print in the javascript.
i.e. @array_example = [1,2,3,4,5] wouldn't work when printed, but @array_example = "[1,2,3,4,5]" would work.

Anyway, The first my question would be, if I have:

<% @chart_posts = Post.where(:user_id => @profile.user.id) %>

Whats a good way to use this data to make an array (if I want the id of each post in the array, and a second array with the created_at)?

To be a little more clear, the final arrary needs to look like an array when printed.
i.e. it must have ['s around it, and ,'s in between each item.

like image 750
Elliot Avatar asked May 09 '26 18:05

Elliot


1 Answers

I'm not too clear on what your final array should look like, but I think map should get you what you need.

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

created_ats = @chart_posts.map(&:created_at) 
# => [timestamp,timestamp,timestamp,timestamp]

You could also combine that into a single 2D array with map as well:

array = @chart_posts.map {|post| [post.id, post.created_at]} 
# => [[1, timestamp],[2,timestamp]]
like image 91
Peter Brown Avatar answered May 11 '26 12:05

Peter Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!