DEV Community

Discussion on: Swapping two numbers, w/o a temp variable

Collapse
 
thepeoplesbourgeois profile image
Josh

Ruby, too! It's been possible at least since 1.8

a, b = b, a
Collapse
 
donut87 profile image
Christian Baer

Oh dear...
The task was to do this "without extra space" and not "don't use an extra variable". Both your solutions fail that. Constructing two arrays is definitely extra space used, you just won't see it in your code.
I don't know what Ruby does, but I can imagine, that this will create some variable 'behind the scene' or will also have to arrays constructed.
I am very sorry, but you both failed the test.
This is not very bad though. In real life you only need to know this kind of 'tricks' when you have very limited hardware like small chips in small devices such as smart lamps or smoke detectors. Also in most applications you probably won't need to switch the values of two variables.

Thread Thread
 
thepeoplesbourgeois profile image
Josh

As always, this is why it's important to understand what the language is doing before calling somebody wrong 🙂

Y'see, no variable in Ruby ever holds the object in question, but instead holds a reference to the object. a, b = b, a tells Ruby to place a reference to whatever is referenced by b at the time of invocation inside of the reference a, and whatever is referenced by a at the time of invocation inside of the reference b. No array construction, no invisible intermediary variable, just happy-go-lucky references, reassigning themselves to the underlying addressed memory locations.

Thx 4 the patronization tho! 💖💖😘

Thread Thread
 
donut87 profile image
Christian Baer

As I said, I am not sure what Ruby does and how this parallel assignment really works under the hood.
For the python example (and this was the main focus), my statement holds :-). It's a construction of an array (list), that is assigned to another list and afterwards deconstructed.

Thread Thread
 
thepeoplesbourgeois profile image
Josh

Good try, but no. "You both fail" is geared quite equally toward two intended audiences. Again, understand what the language is doing before you call someone wrong 😊