I want to make an array with numbers and ranges. Like this:
range = [12, (1..11)]
Which should then look like:
[12, 1, 2, 3...11]
Any suggestions on how to do this?
Here's a shorter version:
[12, *(1..11)] # => [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
It's called the splat operator (in case you didn't know).
So one* way to do this is to say this:
range = [12, (1..11).to_a].flatten
The problem here is that (1..11) isn't an array. It's a range, but I thought that it was an array. So we first have to convert it into an array:
(1..11).to_a
Now, the problem is that we have a multidimensional array. Right?
[12, (1..11).to_a] # => [12, [1, 2, 3...11]]
To convert this into a single array we have to flatten it:
[12, (1..11).to_a].flatten # => [12, 1, 2, 3...11]
Voila!
I'd love to see other people's answers.
*This is one reason why I love Ruby so much.
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