What are the differences between an array and a range in ruby?

arrays, range, ruby

Solution

Firstly, when you're not in the middle of an assignment or parameter-passing, `*(1..10)` is a syntax error because the splat operator doesn't parse that way. That's not really related to arrays or ranges per se, but I thought I'd clear up why that's an error.

Secondly, arrays and ranges are really apples and oranges. An array is an object that's a collection of arbitrary elements. A range is an object that has a "start" and an "end", and knows how to move from the start to the end without having to enumerate all the elements in between.

Finally, when you convert a range to an array with `to_a`, you're not really "converting" it so much as you're saying, "start at the beginning of this range and keep giving me elements until you reach the end". In the case of "(1..10)", the range is giving you 1, then 2, then 3, and so on, until you get to 10.

Problem

just wondering what the subtle difference between an array and a range is. I came across an example where I have `x = *(1..10)` output x as an array and `*(1..10) == (1..10).to_a` throws an error. This means to me there is a subtle difference between the two and I'm just curious what it is.

Original source