locoboy
locoboy

Reputation: 38940

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

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.

Upvotes: 4

Views: 3762

Answers (2)

John Feminella
John Feminella

Reputation: 311526

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.

Upvotes: 10

x1a4
x1a4

Reputation: 19485

One difference is that ranges do not separately store every element in itself, unlike an array.

r = (1..1000000) # very fast
r.to_a # sloooooow

You lose the ability to index to an arbitrary point, however.

Upvotes: 2

Related Questions