2

I'm trying to generate a list that looks like this:

list = [[1, 1], [2, 2], [3, 3], [4, 4], ... [25, 25]]

Is there an easy way to accomplish this with something similar to range?

Update: Looks like .zip wins

  • .map time elapsed 1184.344 milliseconds
  • .zip time elapsed 706.23 milliseconds

Test:

beginning_time = Time.now
(1..2500000).map { |i| [i,i] }
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"

beginning_time = Time.now
(1..2500000).zip 1..25
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
0

4 Answers 4

6

Try this:

(1..25).map { |i| [i,i] }

Output:

[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [10, 10], [11, 11], [12, 12], [13, 13], [14, 14], [15, 15], [16, 16], [17, 17], [18, 18], [19, 19], [20, 20], [21, 21], [22, 22], [23, 23], [24, 24], [25, 25]]
Sign up to request clarification or add additional context in comments.

Comments

3
(1..25).zip 1..25
#=> [[1, 1], [2, 2], [3, 3], [4, 4] ...

Comments

1

Try this:

Array.new(25){|i| [i+1, i+1]}

Comments

1

Ok, 2 hours late, and, just to be different...

[[*1..25], [*1..25]].transpose
# => [[1, 1], [2, 2], [3, 3], [4, 4], ...

...or...hehe...

([[*1..25]]*2).transpose

Comments

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.