1

I'd like to "explode" an array in Ruby in order to do a fast variable assignment i.e.

a, b = ['first_var', 'second_var']

Is this possible? I've looked through the array docs and can't find anything that seems to offer this but it seems Rubyish...

3
  • 1
    The code you've written should work exactly as you've written it. What exactly are you looking for? What is it you think is wrong with the code you've posted? Commented Dec 14, 2011 at 16:30
  • Not sure what you're asking; the snippet you wrote works as-is. Commented Dec 14, 2011 at 16:30
  • Ahh, not quite sure why that passed me by. Nice to see I've got an intuitive grasp of the language though Commented Dec 14, 2011 at 16:37

1 Answer 1

4

This works as you would expect. Note that you can use * to slurp up extra right hand side elements, whereas extra elements on the left hand side will be set to nil:

>> range = *1..10 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> a, b = range #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> [a, b] #=> [1, 2]
>> a, *b = range #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> b #=> [2, 3, 4, 5, 6, 7, 8, 9, 10]
>> a, b, c = 1,2 #=> [1, 2]
>> c #=> nil
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.