Reputation: 5559
I'm trying to create an array of arrays to be used in a JavaScript function.
Here is the format of the array that I'm trying to create:
[[1,1],[2,3],[3,6],[4,10],[5,15],[6,21]]
Here is the ruby code to create the array:
total=0
foo=[]
(1..6).each do |number|
foo.push [number, total+=number]
end
puts foo
Here is the output of puts foo
:
1
1
2
3
3
6
4
10
5
15
6
21
Any ideas how to output the correctly formatted array?
Upvotes: 0
Views: 121
Reputation: 2311
Change puts foo
to foo.inspect
total=0
foo=[]
(1..6).each do |number|
foo.push [number, total+=number]
end
foo.inspect
Upvotes: 1
Reputation: 27802
You can use p foo
to print out the array:
total=0
foo=[]
(1..6).each do |number|
foo.push [number, total+=number]
end
p foo
This prints out: [[1, 1], [2, 3], [3, 6], [4, 10], [5, 15], [6, 21]]
Upvotes: 0
Reputation: 18543
If I understand that correctly, you want to output the array somewhere in a document to be interpreted as JavaScript by the browser.
When it comes to using Ruby objects in JavaScript, you can use the JSON gem.
require 'json'
#create the array
foo.to_json
should do the trick.
This also works for hashes and some other object types.
Upvotes: 2