tags:

views:

78

answers:

2

I think the answer is simply, "no you can't do that," but my thoughts are pretty much always wrong about Ruby.

I'm trying to do this in Ruby

city, state, zip = (0..2)

this results in city being a Range and the others being nil, which is not what I want. Is there any way to do this?

+6  A: 

Yes

city, state, zip = *(0..2)
Dario
Ooh I never thought of using the splat operator for assignment...
guns
+1, thanks Dario...
Yar
+8  A: 

With splat operator

city, state, zip = *(0..2)

With cast to array

city, state, zip = (0..2).to_a
Simone Carletti
Perfect, thanks!
Yar
So what is the difference between splat and to_a? At least in this case, the result is always an array.
Yar
There's no difference in this case. In practical terms, the splat operator essentially replaces an Enumerable with its constituent elements. So if you write `[*[1,2], *[3], 4]`, the result is `[1,2,3,4]`.
Chuck