Over a million developers have joined DZone.

Swap Elements Of An Array In Ruby

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

class Array
    def swap!(a,b)
         self[a], self[b] = self[b], self[a]

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.

The Web Dev Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}