Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby making an array with numbers and ranges

Tags:

arrays

range

ruby

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?

like image 849
irosenb Avatar asked Sep 22 '26 10:09

irosenb


2 Answers

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).

like image 110
Sergio Tulentsev Avatar answered Sep 24 '26 00:09

Sergio Tulentsev


So one* way to do this is to say this:

range = [12, (1..11).to_a].flatten

Explanation

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.

like image 32
irosenb Avatar answered Sep 24 '26 00:09

irosenb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!