0

Let's say I have a number 5

How would I convert this to an array [1, 2, 3, 4, 5]?

The application here is I have an instance variable @pages and I want to create a pagination view.

mridula
  • 3,203
  • 3
  • 32
  • 55
Abe
  • 6,386
  • 12
  • 46
  • 75

2 Answers2

3
pages = 5
array_of_numbers = (1..pages).to_a

(1..pages) will give you a Range object and to_a will convert it into an array.

mridula
  • 3,203
  • 3
  • 32
  • 55
0

https://apidock.com/ruby/Integer/times pointed me to a solution

pages = 5 (1..pages).each { |n| puts n }

Abe
  • 6,386
  • 12
  • 46
  • 75
  • 1
    You have a lot of other ways in [older answers](https://stackoverflow.com/questions/191329/correct-way-to-populate-an-array-with-a-range-in-ruby/6587096). I guess isn't necessary to create a new question for that. – Sebastián Palma Dec 22 '18 at 13:13
  • This won't return an array. It will just print the nos. – mridula Dec 22 '18 at 15:20