Adam Fields (work stuff) RSS

This is my blog about work stuff.

See this post for discussion of what this blog is about and what I do.

I am often available for consulting work, and always happy to discuss it even if I'm currently very busy. Email me or find me on twitter @fields if you need something.

Archive

Apr
17th
2011
Sun
permalink

How to swap two variables without using a third (ruby edition)

Method 1:

> string1 = "sssss"
 => "sssss" 
> string2 = "ttttt"
 => "ttttt" 
> string1, string2 = string2, string1
 => ["ttttt", "sssss"] 
> string1
 => "ttttt" 
> string2
 => "sssss" 
Method 2:
> string1 = "sssss"
 => "sssss" 
> string2 = "ttttt"
 => "ttttt" 
> string1 = [string1, string2]
 => ["sssss", "ttttt"] 
> string2 = string1[0]
 => "sssss" 
> string1 = string1[1]
 => "ttttt" 
> string1
 => "ttttt" 
> string2
 => "sssss"
It’s probably worth noting that I’ve never once needed to do this in 15 years of programming for a living.

Comments (View)

blog comments powered by Disqus