Over a million developers have joined DZone.

Swap Elements Of An Array In Ruby

DZone's Guide to

Swap Elements Of An Array In Ruby

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

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.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}