Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to populate an Array with a Range in Ruby

Tags:

syntax

ruby

I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods

When i run the code in irb I get the following warning

 warning: default `to_a' will be obsolete 

What is the the correct alternative to using to_a?

are there alternate ways to populate an array with a Range?

like image 472
Willbill Avatar asked Oct 10 '08 13:10

Willbill


People also ask

Is a range an array in Ruby?

Yes, the method does look like an array class. However, you need to add a pair of parenthesis to let Ruby know you are using the Array method and not the class. The resulting value is the range of values in an array format.

How do you write a range in Ruby?

Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.

How do you add multiple values to an array in Ruby?

Appending or pushing arrays, elements, or objects to an array is easy. This can be done using the << operator, which pushes elements or objects to the end of the array you want to append to. The magic of using << is that it can be chained.


1 Answers

You can create an array with a range using splat,

>> a=*(1..10) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

using Kernel Array method,

Array (1..10) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

or using to_a

(1..10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
like image 66
Zamith Avatar answered Sep 19 '22 19:09

Zamith