DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Swap Elements Of An Array In Ruby

05.13.2005
| 18986 views |
  • submit to reddit
        
class Array
    def swap!(a,b)
         self[a], self[b] = self[b], self[a]
    self
    end
end

You can now do stuff like..

[1,2,3,4].swap!(2,3)  # = [1,2,4,3] etc..

Many thanks to Sam Stephenson and technoweenie for their suggestions.    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:12pm

try this: self[a], self[b] = self[b], self[a]