Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Swap Elements Of An Array In Ruby

DZone's Guide to

Swap Elements Of An Array In Ruby

· Web Dev Zone ·
Free Resource

Learn how Crafter’s Git-based content management system is reinventing modern digital experiences. Download this white paper now. 

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.

Crafter CMS is a modern Git-based platform for building innovative websites and content-rich digital experiences. Download this white paper now.

Topics:
ruby

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}