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?
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With