0

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?

4
  • 3
    did you try foo.inspect or foo ? Commented Jul 31, 2013 at 15:44
  • your code works - you have the desired array in foo :) Commented Jul 31, 2013 at 15:46
  • Under Ruby 1.8, to_s is equivalent to join, but in 1.9+ it's equivalent to calling inspect. Commented Jul 31, 2013 at 16:00
  • This question needs a clearer description of the what (the desired output) and the why (for what reason do you want the output formatted like that?) Commented Mar 2, 2014 at 17:39

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The JSON library should be included by default in environments like Rails.
1

Change puts foo to foo.inspect

total=0
foo=[]
(1..6).each do |number|
  foo.push [number, total+=number]
end
foo.inspect

1 Comment

foo.inspect over foo.to_s is better for the general case.
0

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

2 Comments

p writes this to STDOUT so it's completely useless when trying to render a web page.
No one was talking about the web and OP used puts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.